Memory management in JavaScript

Garbage collection:

JavaScript has an automatic garbage collection mechanism, the execution environment is responsible for managing the memory used during code execution, and the required memory is automatically managed. Principle: Find out the variable of the memory that is no longer in use, and then release its memory. For this reason, the garbage collector will periodically perform this operation at regular intervals.
The normal life cycle of local variables: Local variables only exist during the execution of the function. Allocate corresponding space on the stack (or heap) memory where local variables are located to store their values, and use these values ​​inside the function until the function ends. After the function ends, they no longer need to exist, and their memory can be released.

Clear mark:

The most commonly used garbage collection in JavaScript is "mark removal" (for example, declaring a variable in a function and marking this variable as entering the execution environment). When a variable enters the execution environment, the memory it occupies cannot be released, and it can be released when it leaves the execution environment.

Manage memory:

Using a language with garbage collection mechanism to write programs, developers generally do not have to worry about memory management issues, but the problem faced in memory management in JavaScript is that the amount of available memory allocated to web browsers is usually less than that allocated to desktop applications , The purpose of this is mainly for safety considerations, to prevent JavaScript web pages from running out of memory and causing system crashes; memory limitation issues will not only affect variable allocation memory, but also affect the call stack and the simultaneous execution in a thread Number of sentences.
Therefore, ensuring that the least memory is used can make the page get better performance, and the best way to optimize the memory usage is to save only the necessary data in the execution statement. Once the data is no longer used, it is best to set its value to null to release memory. This method is suitable for most global variables and global objects. Local variables are automatically dereferenced when they leave the scope.
example:

function createA(num){
   var B = new object();
B.num = num;
       return B;
}
// 局部变量离开后已自动解除
// 赋值给全局变量C
var C  =  createA(“66”);
// 手动解除对C的引用
C = null;

However, dereferencing a value does not mean that the memory occupied by the value is reclaimed. The real effect of dereference is to get the value out of the execution environment so that the garbage collector can reclaim it the next time it runs.

Guess you like

Origin blog.csdn.net/Jonn1124/article/details/108808464