Preface strong>
JS has an automatic garbage collection mechanism, in other words, the execution environment manages the memory used during code execution.
The principle of JS garbage collection
The execution environment will find out those that are not Then continue to use the variable, and then release the memory it occupies.
JS Garbage Collection Strategy
Marker Clear
strong>
When a variable enters the environment, it is marked as “entering the environment”, and when the variable leaves the environment, it is marked as “leaving the environment”.
The way to mark variables depends on the specific implementation. For example, you can use a “enter environment” variable list and a “leave environment” variable list to track which variable has changed.
Browsers that have used tag clearing include IE, Firefox, and chrome.
Reference counting
This is a less common garbage collection strategy, which is to track the number of times each value is referenced.
When a variable a is declared and a reference type value ({name:'cc'}) is assigned to the variable, the number of references to this value is 1, if a ({name:'cc'}) is assigned to another variable b, then the number of references to this value will increase by 1. Conversely, if a is assigned {name:'xx'}, then the reference count of {name:'cc'} will be reduced by 1. When the number of references to the value of {name:'cc'} becomes 0, it means that there is no way to access the value of {name:'cc'}, so it can be The occupied memory space is reclaimed. In this way, when the garbage collector works, the memory space occupied by the value of {name:’cc’} will be reclaimed.
This method has been used by Netscape Navigator 3.0, but there is a serious problem: circular reference.
function circleReferenceProbem(){ let objectA = new Object() let objectB = new Object() objectA.someOtherObject = objectB objectB. anotherObject = objectA }
After executing this function, because the reference count of these two reference values will never be 0, the garbage collector will never reclaim the memory space they occupy.
The performance of the JS garbage collector
Because the JS garbage collector is Garbage collection is performed every other cycle.
If the amount of memory allocated for variables is not large, then the garbage collector’s recovery workload is not large. However, when the workload of the garbage collector is too large, it is likely to be stuck.
Suggestions for managing memory in JS
1. Try to use less global Variables
2. Manually clear variable references as much as possible
Recommended tutorial: “JS Tutorial”
The above is a quick understanding of the details of Javascript garbage collection, more please pay attention 1024programmer.com Other related articles!