Preface
js has an automatic garbage collection mechanism. In other words, the execution environment will manage 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 clear
When a variable enters the environment, this variable will be Marked as "entering the environment", and when a 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 "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
Use global variables as little as possible
Manually clear references to variables whenever possible
Thanks for reading!
If you need to communicate on WeChat, you can leave a message!
Recommended tutorial: "JS Tutorial"
The above is the detailed content of Understand the garbage collection mechanism of js in seconds. For more information, please follow other related articles on the PHP Chinese website!