Js garbage collection mechanism
concept
Js memory is allocated and reclaimed automatically. When it is not used, it will be reclaimed automatically by garbage collector. However, we need to understand the mechanism of garbage collection to prevent memory leakage (memory cannot be reclaimed).
The life cycle
Memory creation allocation: apply variables, objects, functions, etc
Memory usage: Reading and writing memory, that is, using variables, function objects, etc
Memory destruction: variables, functions, objects, etc. are no longer used, that is, they are automatically collected by garbage collection
The core algorithm
Check whether the memory is no longer in use. If so, reclaim it
Reference counting
Ie uses reference counting
Count the number of times the memory is referenced. The number of times the memory is referenced is +1, and the number of times the memory is not referenced is -1. When the number is 0, the memory is released and reclaimed
var a = { name: 'Joe'.age: 'bill' }// a address => {name: 'zhang ', age:' li '
var b = a // b address => {name: 'zhang ', age:' li '
var c = a // c address => {name: 'zhang3 ', age:' zhang4 '
a = 1
b = null
c = true
Copy the code
Advantages: Simple and effective Problem: Memory leaks due to circular references
Analysis of the above picture:
- Function call, create a address to a memory (memory 1), b address to a memory (memory 2)
- A.a1 also points to memory 2, and b.b1 points to memory 1
- In this case, memory 1 is referenced by A and B. 1 and counts 2
- In this case, memory 2 is referenced by b and a.a1 and counts 2
- After the fn function call is executed, the internal data of FN is no longer used, so it needs to be reclaimed. A points to memory 1 and B points to memory 2
- Memory 1 is also referenced by b.b1 and count 1 cannot be collected
- Memory 2 is also referenced by a. 1. Count 1 cannot be collected
Conclusion: No. 1 memory and No. 2 memory can not be reclaimed for circular reference, resulting in memory leakage
Mark clearly
Browsers now use tag clearing
A tag marks all objects accessible from the root node (global). Unmarked objects are junk objects that are not globally referenced.
Eventually all unmarked objects are cleared
function fn() {
var a = {}
var b = {}
a.a1 = b
b.b1 = a
}
fn()
Copy the code
Since the data inside the fn function is not globally accessible, the data inside the function is automatically cleared after fn is executed
function fn() {
var a = {}
var b = {}
a.a1 = b
b.b1 = a
return a
}
var obj = fn()
Copy the code
After the fn function is called, the data inside the fn function is referenced globally, and the data inside the FN function is used by the DATA inside the B function, so the data inside the FN function is not cleared