Talk about garbage collection mechanism

Lead our protagonist

Let us first recall that global variables, the system will release the memory occupied when the page is closed, function local variables, will release the memory when the function is executed, this is our protagonist today: Js garbage collection mechanism .

All languages ​​need to handle this process. For example, C language requires developers to manually apply and release memory

And  Javascript automatically helps us with memory management , completing the entire memory management life cycle, allowing developers to focus on the business logic itself

But at the same time it also created the illusion of memory management for developers .

Summarize this process :

  • Allocate the memory you need
  • Use allocated memory (read, write)
  • Release\return it when not needed

Here are two important points of garbage collection:

  • Memory leak
When some memory is no longer needed, for some reason, it cannot be released. It will cause a memory leak , causing the program memory is occupied, until the collapse.
  • Accessibility
The standard of garbage collection is whether the object is reachable and whether the variable can be referenced

Quote

The memory address of the object {name: xxx} is referenced twice by the variables a and b. When a is assigned a value of null, because b is still being referenced and reachable, it is not recycled

var a = { name: "小红"};
var b = a;
a.name = "小黑";
console.log(b)
a = null;
console.log(b)
b = null; 

When test1()executed, the system allocates memory for obj, and when the function is executed, the memory is reclaimed.

When test2()obj is executed, memory is also opened up, but obj is assigned to b by the returned result, which becomes a global variable and will not be destroyed

function test1 () {
      var obj = {}
}
​
function test2 () {
      var obj = {}
      return obj
}
​
const a = func1()
const b = func2()

Introduce two commonly used methods of garbage collection:

1. Reference removal (adopted before IE9)

The number of times the variable is referenced after declaration. When it is 0, the variable memory is destroyed

function test () {
      var a = {} //  a的引用计数为 0,
      var b = a // a 被 b 引用 a引用计数为 1
      let c = a // a 被 c 引用 a引用计数为 2
      b = null // b 不再引用a a的引用计数减为 1
      c = null // c不再引用a a的引用计数减为 0 被回收
}

advantage

  • Immediately collect garbage, when the referenced value is 0, it will be collected immediately
  • No need to traverse all active and inactive objects in the heap

Disadvantage

  • The counter needs to occupy a large space, because the upper limit of being quoted cannot be estimated
  • The biggest disadvantage is that it cannot solve the problem that circular references cannot be recycled
function problem(){
    var a = new Object();
    var b = new Object();
    a.test = b;
    b.test = a;
}

The above a and b refer to each other, the count will not be equal to 0, the memory will not be recycled, repeated calls will occupy a lot of memory

2. Inside the V8 engine (basically adopted now, with the mark cleared)

It is Javascriptadopted by the parsing engine V8 in the browser . The marking stage: Mark all active objects, and destroy the unmarked (that is, inactive objects).

From the variables in the global scope, traverse in depth layer by layer along the scope. When it is found to be referenced, mark it, and after the execution is completed, the variable memory that is not marked will be destroyed.

 

 

Talk about common memory leaks

When Foo is called, this points to a global variable (window), which is equivalent to a global variable, and the variable will not be recycled

function test() {
    this.test = "lala";
}
foo();

When the node is killed, the timer will continue to execute

setInterval(function() {
    var node = document.getElementById('div');
    if(node) {
        node.innerHTML = "!。。。。。。。"
    }
}, 5000); 

Closure

counter

It achieves increment without polluting the global environment. The child function references the parent function variable num, and num will not be recycled after the parent function is executed. When the child function is executed, it returns to the outermost global environment variable add and records the status. This is actually memory Leak case

var add = (function () {
    var num = 0;
    return function () {
        return ++num;
    };
  })();
console.log(add());
console.log(add());
console.log(add());

Turn off memory management

  • Generally stack storage (value of basic type) will not leak, heap storage (value of reference type is object) will cause leakage
  • Generally, small memory leaks will not affect the program, but for large-scale projects, prevent the accumulation of too little, and develop good programming habits

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/108600091