Home > Web Front-end > JS Tutorial > body text

What is the use of memory in js? Understand the role of js memory

不言
Release: 2018-08-16 15:09:25
Original
1511 people have browsed it

The content of this article is about what is the use of memory in js? It has certain reference value to understand the role of js memory. Friends in need can refer to it. I hope it will be helpful to you.

In the process of JS development, understanding the JS memory mechanism helps developers clearly understand what happened during the execution of the code they wrote, and can also improve the code quality of the project.

What does JS memory look like?

Variable storage in JS is divided into original values ​​and reference values:

  • Original value: original data type : undefined, null, number, string, boolean and the new symbol# added by es6 ##.

  • ##Reference value: Values ​​of types such as
  • object

    , array, function are reference values.

  • Memory in JS is also divided into stack memory and heap memory. For detailed information on heap and stack, see here.
eg:

const str = '我是说明内存的文档'; // 这里 str 以及 '我的说明内存的文档' 都存储在栈内存当中
const obj = { a: 1 }; // 这里 obj(指向存储在堆中的数据的指针) 是存储在栈内存 而 { a: 1 } 则存储在堆当中
Copy after login

Storage objects in memory What is the declaration cycle?

Introduction in MDN:

    Allocate memory for the object when it will be needed.
  1. Use allocated memory (read and write operations)
  2. When the object is no longer needed, release the memory storing this object
1

2It’s the same in all languages, 3It’s not so obvious in JSLook at the memory What happened?

let str1 = 1; // 为str1分配栈内存 str1: 1
let str2 = str1; // 原始类型直接访问值, 即为str2新分配栈内存: str2: 1

str2 = 2; // 栈内存: str2: 2. str2的值为2, 而str1的值仍然是1

/************************ 我是分割线: 上面为原始类型 下面为复杂类型 *******************************/

let obj1 = { a: 1 }; // 为obj1分为栈内存访问地址的指针: obj1. 堆内存中存储对象值: { a: 1 }
let obj2 = obj1; // 为obj2分配栈内存访问地址的指针: obj2. 引用了堆内存中的值{ a: 1 }

obj2.a = 2; // 通过obj1修改堆内存的数据, 由于obj2与obj2都是指向堆内存中的同一个数据的指针(也叫引用). 所以堆内存中的值{a: 1}修改为{a: 2} 即 obj1.a 为 2; obj2.a 也为 2; (这里它们是指向了堆内存中的同一个数据的不同指针)

obj2 = { a: 3 }; // 因为改的是整个对象, 这里会在堆内存中创建一个新的对象值: {a:3}, 而obj2引用的是这个新对象, 所以obj1.a 依旧为 2; 而obj2.a 则为 3了. (这里它们是指向了堆内存中的不同数据的不同的指针)
Copy after login

Then look at this question:

let a = { n: 1 };
let b = a;
a.x = a = { n: 2 };
Copy after login

Looking at the detailed explanation is very helpful for understanding the basic knowledge points. For example: The order of assignment operations in js is always It is from right to left, but

.

is the operator with the highest priority.From the perspective of memory, changes in the value passed by the function

About passing value/address Explanation. Use primitive types and reference types to distinguish. The primitive type passes the value, and the reference type passes the address.

let str = '我是初始字符串';
let fn = (arg) => {
    console.log(arg); // #1 我是初始字符串

    arg = '我是修改后的字符串';
    console.log(arg); // #2 我是修改后的字符串
    console.log(str); // #3 我是初始字符串
};
fn(str);
Copy after login

In the above example

#1

you can see the incomingfn is the value of str, and new space is allocated in the stack memory to save the function parameters and their values ​​(this part of the memory is automatically released after the function is run, _garbage collection mechanism_). So the output value in #2 is I am the modified string . Pass the parameter arg when calling the function fn The value (newly allocated data in stack memory), and str is the original type. The output at #3 is consistent with the initialization definition.<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">let obj = { a: 1 }; let fn = (arg) =&gt; {     arg = { a: 2 }; }; fn(obj); // 这个时候obj还是{a: 1} let fn1 = (arg) =&gt; {     arg.a = 2; }; fn1(obj); // 这个时候obj则为{a: 2}</pre><div class="contentsignin">Copy after login</div></div> Both functions in the above example are passed by address. The parameters

arg

initially passed in are references (pointers pointing to the same data in the heap memory), in fn Reassign a new object (reference type) to variable arg. And arg in fn1 is still a reference (pointer to data in heap memory), So fn1 is modified successfully. Garbage collection mechanism

JS has a garbage collection mechanism, which brings great convenience to developers, at least it doesn’t require too much Consider the issue of memory release (some still need to be considered).

    The variables of the function only exist during the execution of the function. During the execution of the function, the variables inside the function will be in A certain amount of space is allocated in the memory. When the function is executed, these variables are automatically released from the memory to leave space for other uses.
  • When a variable in the memory is no longer is referenced, JS will clean up the allocation of this part of the memory. eg:
  • let obj = { a: 1 }; // 内存中存在{a: 1}对象, 以及obj这个引用地址
    obj = { a: 2 }; // 垃圾回收机制自动清理{a: 1}, 并为新的有用的{a: 2}分配空间
    Copy after login
  • Memory Optimization

As far as global variables are concerned, JS cannot determine whether it will be used later. So, it will always exist in memory from the time it is declared until it is manually released or the page/browser is closed, which leads to some unnecessary memory consumption. We can make the following optimizations.

Use Immediately Execution function

(() => {
    // do something...
})();
Copy after login

Manually touch the reference of the variable

let obj = { a: 1, b: 2, c: 3 };
obj = null;
Copy after login
In JS, closures are the most likely to cause memory problems. We can use callback functions instead Closures are used to access internal variables. The advantage of using callbacks is that (the internal variables accessed are values ​​of primitive types, because values ​​are passed when the function passes parameters), the variables will be automatically released after execution, and will not be like Closures always keep internal variables in memory (but if it is a reference type, then the referenced object is still in memory).

function fn() {
    var val = '你好';
    return function() {
            return val
        };
};
var getVal = fn();
var v = getVal(); // 你好
Copy after login

In the above example, although the function

fn

The execution has been completed, but the reference to the variable val in the function is still there, so the garbage collection mechanism will not recycle the val in the function.

is used Callback

function fn1(cb) {
    var val = '你好';
    return cb(val);
};
function fn2(arg) {
    return arg;
};
var v = fn1(fn2);
Copy after login
Declared at the same time, it does not mean that doing so is necessarily better than closure. Closure also has its benefits, but we just need to distinguish between using it at the most appropriate time.

Related recommendations:

JS memory management example explanation


Analysis of memory release method in JS class library Bindows1.3_javascript skills


JS memory management example explanation

The above is the detailed content of What is the use of memory in js? Understand the role of js memory. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template