Home > Article > Web Front-end > Quickly understand JavaScript garbage collection
Preface
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 those variables that are no longer used, and then release the memory they occupy.
JS garbage collection strategy
Mark clearing
When a variable enters the environment, it Mark this variable as "entering the environment" and when the variable leaves the environment, mark it as "leaving the environment".
The way to mark variables depends on the specific implementation. For example, you can use a "entering the environment" variable list and a "leaving the environment" variable list to track which variables have changed.
Browsers that have used tag removal include IE, Firefox, and chrome.
Reference counting
This is a less common garbage collection strategy, which tracks 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 is increased by 1. On the contrary, if a is assigned the value {name:'xx'}, the number of references to the value {name:'cc'} is reduced by 1. When the number of references to the value {name:'cc'} becomes 0, it means that there is no way to access the value {name:'cc'} anymore, so the memory space occupied by it can be recycled. In this way, when the garbage collector works, the memory space occupied by the value {name:'cc'} will be recycled.
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 number of references of these two reference values will never be 0, the garbage collector will never reclaim the memory space they occupy.
Performance of JS garbage collector
Because the JS garbage collector performs garbage collection every other cycle.
If the amount of memory allocated for the variable is not large, then the garbage collector's recycling workload will not be large. However, when the workload of the garbage collector is too large, lags are likely to occur.
Suggestions for managing memory in JS
1. Use global variables as little as possible
2. Clear variables manually as much as possible Reference
Recommended tutorial: "JS Tutorial"
The above is the detailed content of Quickly understand JavaScript garbage collection. For more information, please follow other related articles on the PHP Chinese website!