preface
Js has automatic garbage collection, in other words, the execution environment manages the memory used during code execution.
Js garbage collection principle
The execution environment finds variables that are no longer in use and frees their memory.
Js garbage collection strategy
Mark clear
The variable is marked as “in” when it enters the environment and “out” when it leaves the environment.
The way variables are marked depends on the implementation, for example, you can use a list of variables that are “in” and a list of variables that are “out” to track which variables have changed.
Browsers that have used tag clearing include Internet Explorer, Firefox, and Chrome.
Reference counting
A less common garbage collection strategy is to keep track of how many 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 the value is 1. If a ({name:’cc’}) is assigned to another variable B, the number of references to the value is increased by 1. Conversely, if a assigns {name:’xx’}, the number of references to {name:’cc’} is reduced by one. When the number of references to {name:’cc’} becomes zero, then there is no way to access {name:’cc’}, so it can be reclaimed. This way, when the garbage collector works, the memory space occupied by {name:’cc’} is reclaimed.
This approach was used by Netscape Navigator 3.0, but there was a serious problem: circular references.
function circleReferenceProbem() {let objectA = new Object()
let objectB = new Object()
objectA.someOtherObject = objectB
objectB.anotherObject = objectA
}
Copy the code
After executing this function, the garbage collector will never reclaim the memory space occupied by the two reference values because they are never referenced zero times.
Js garbage collector performance
Because the JS garbage collector performs garbage collection every other cycle.
If the amount of memory allocated for variables is small, then the garbage collector does not do much collecting. However, when the workload of the garbage collector becomes too heavy, it is likely that the situation will stall.
Suggestions for managing memory in js
- Use global variables as little as possible
- Manually clear references to variables whenever possible
Thanks for reading!
Need to add wechat communication, can leave a message!