Reference count in JS garbage collection mechanism

window.onload = function(){
    var el = document.getElementById("id");
    el.onclick = function(){
        alert(el.id);
    }
}
window.onload=function outerFunction(){
    var obj = document.getElementById("element");
    obj.onclick=function innerFunction(){};
}

this code looks fine, but obj refers to document.getElementById ("element"), and the onclick method of document.getElementById ("element") refers to variables in the external environment, which naturally includes obj,. How do you understand these two circular references?

Feb.27,2021

I tested it with V8. During garbage collection, the scope of the external environment will not be completely preserved, only the variables referenced by the function will be left, which is estimated to be optimized by variable analysis.

The

obj.onclick=function innerFunction () {} , innerFunction function does not refer to anything.

Circular references are similar

  var o = {};
  var o2 = {};
  o.a = o2; // o  o2
  o2.a = o; // o2  o

this variable is never cleared when counting is used. In the past, it was mostly cleared by directly assigning null to variables.

since 2012, all modern browsers have used the tag-clear garbage collection algorithm.
this algorithm simplifies "whether the object is no longer needed" to "whether the object is available".

this algorithm assumes that an object called root (root) is set (in Javascript, the root is a global object). Periodically, the garbage collector will start from the root, find all the objects referenced from the root, and then find the objects referenced by these objects. Starting from the root, the garbage collector will find all available objects and all unavailable objects.

memory Management

look at the garbage collection notes of "Node profound and simple":

clipboard.png

clipboard.png

clipboard.png


this actually involves the concept of scope and closure. The method of el.onclick and obj.onclick is actually a new scope, and then the method is actually a function outside outerFunction, because DOM listening events cannot be locally scoped, but are globally scoped. This constitutes a condition of a closure, which can access private variables inside the function through external calls. That is, it can access the variables in outerFunction, so it indirectly refers to the el,obj variables in the active variables of outerFunction. In addition, the property onclick in el,obj points to the memory area where the anonymous function is located, which leads to cross-reference circular references

.
Menu