Home  >  Article  >  Web Front-end  >  Comprehensive understanding of JavaScript's garbage collection mechanism_Basic knowledge

Comprehensive understanding of JavaScript's garbage collection mechanism_Basic knowledge

亚连
亚连Original
2018-05-19 16:39:30952browse

Below I will bring you a comprehensive understanding of JavaScript's garbage (garbage collection) recycling mechanism. Let me share it with you now and give it as a reference for everyone.

1. Garbage Collection Mechanism—GC

Javascript has an automatic garbage collection mechanism (GC: Garbage Collection), which means that the execution environment will be responsible for managing the code execution process memory used in.

Principle: The garbage collector will periodically (periodically)find out those variables that are no longer in use, and then release their memory.

The mechanism of JavaScript garbage collection is very simple: find the variables that are no longer used, and then release the memory they occupy. However, this process is not real-time because its overhead is relatively large, so the garbage collector will follow the fixed Periodic execution at a certain time interval.

Variables that are no longer used are variables whose life cycle has ended. Of course, they can only be local variables. The life cycle of global variables will not end until the browser unloads the page. Local variables only exist during the execution of the function. During this process, corresponding space is allocated on the stack or heap for local variables to store their values. These variables are then used in the function until the end of the function, and the closure Due to internal functions in the package, external functions cannot be considered the end.

Let’s explain the code:

function fn1() {
 var obj = {name: 'hanzichi', age: 10};
}
 
function fn2() {
 var obj = {name:'hanzichi', age: 10};
 return obj;
}
 
var a = fn1();
var b = fn2();

Let’s see how the code is executed. First, two functions are defined, called fn1 and fn2 respectively. When fn1 is called, entering the environment of fn1, a memory will be opened to store the object {name: 'hanzichi', age: 10}, and when the call is completed, the fn1 environment, then this block of memory will be automatically released by the garbage collector in the js engine; during the process of fn2 being called, the returned object is pointed to by the global variable b, so this block of memory will not be released.

The question arises here: Which variable is useless? Therefore, the garbage collector must keep track of which variables are useless and mark variables that are no longer useful to prepare for reclaiming their memory in the future. The strategy used for marking unused variables may vary from implementation to implementation, but generally there are two implementations: mark-sweeping and reference counting. Reference counting is less commonly used, mark-and-sweep is more commonly used.

2. Mark clearing

The most commonly used garbage collection method in js is mark clearing. When a variable enters the environment, for example, by declaring a variable in a function, the variable is marked as "entered the environment." Logically, the memory occupied by variables entering the environment can never be released, since they may be used whenever the execution flow enters the corresponding environment. And when a variable leaves the environment, it is marked as "leaving the environment".

function test(){
 var a = 10 ; //被标记 ,进入环境 
 var b = 20 ; //被标记 ,进入环境
}
test(); //执行完毕 之后 a、b又被标离开环境,被回收。

The garbage collector will mark all variables stored in memory when it runs (of course, any marking method can be used). Then, it removes the tags (closures) of variables in the environment and variables referenced by variables in the environment. Variables that are marked after this will be regarded as variables to be deleted because variables in the environment can no longer access these variables. Finally, the garbage collector completes the memory cleanup work, destroying those marked values ​​and reclaiming the memory space they occupy.

So far, the js implementations of IE, Firefox, Opera, Chrome, and Safari all use mark-and-clear garbage collection strategies or similar strategies, but the garbage collection time intervals are different from each other.

3. Reference Counting

The meaning of reference counting is to track and record the number of times each value is referenced. When a variable is declared and a reference type value is assigned to the variable, the number of references to this value is 1. If the same value is assigned to another variable, the reference count of the value is increased by 1. Conversely, if the variable containing a reference to this value obtains another value, the number of references to this value is decremented by one. When the number of references to this value becomes 0, it means that there is no way to access this value anymore, so the memory space it occupies can be reclaimed. In this way, when the garbage collector runs next time, it will release the memory occupied by those values ​​​​with a reference count of 0.

function test(){
 var a = {} ; //a的引用次数为0 
 var b = a ; //a的引用次数加1,为1 
 var c =a; //a的引用次数再加1,为2
 var b ={}; //a的引用次数减1,为1
}

Netscape Navigator3 was the first browser to use the reference counting strategy, but soon it encountered a serious problem: circular references. A circular reference means that object A contains a pointer to object B, and object B also contains a reference to object A.

function fn() {
 var a = {};
 var b = {};
 a.pro = b;
 b.pro = a;
}
 
fn();

The reference times of the above codes a and b are both 2. After fn() is executed, both objects have left the environment. There is no problem in the mark and clear mode, but under the reference counting strategy , because the number of references to a and b is not 0, the memory will not be reclaimed by the garbage collector. If the fn function is called in large numbers, it will cause a memory leak. On IE7 and IE8, memory skyrocketed.

我们知道,IE中有一部分对象并不是原生js对象。例如,其内存泄露DOM和BOM中的对象就是使用C++以COM对象的形式实现的,而COM对象的垃圾回收机制采用的就是引用计数策略。因此,即使IE的js引擎采用标记清除策略来实现,但js访问的COM对象依然是基于引用计数策略的。换句话说,只要在IE中涉及COM对象,就会存在循环引用的问题。

var element = document.getElementById("some_element");
var myObject = new Object();
myObject.e = element;
element.o = myObject;

这个例子在一个DOM元素(element)与一个原生js对象(myObject)之间创建了循环引用。其中,变量myObject有一个名为element的属性指向element对象;而变量element也有一个属性名为o回指myObject。由于存在这个循环引用,即使例子中的DOM从页面中移除,它也永远不会被回收。

看上面的例子,有同学回觉得太弱了,谁会做这样无聊的事情,其实我们是不是就在做

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

这段代码看起来没什么问题,但是obj引用了document.getElementById(“element”),而document.getElementById(“element”)的onclick方法会引用外部环境中德变量,自然也包括obj,是不是很隐蔽啊。

解决办法

最简单的方式就是自己手工解除循环引用,比如刚才的函数可以这样

myObject.element = null;
element.o = null;
window.onload=function outerFunction(){
 var obj = document.getElementById("element");
 obj.onclick=function innerFunction(){};
 obj=null;
};

将变量设置为null意味着切断变量与它此前引用的值之间的连接。当垃圾回收器下次运行时,就会删除这些值并回收它们占用的内存。

要注意的是,IE9+并不存在循环引用导致Dom内存泄露问题,可能是微软做了优化,或者Dom的回收方式已经改变

四、内存管理

1、什么时候触发垃圾回收?

垃圾回收器周期性运行,如果分配的内存非常多,那么回收工作也会很艰巨,确定垃圾回收时间间隔就变成了一个值得思考的问题。IE6的垃圾回收是根据内存分配量运行的,当环境中存在256个变量、4096个对象、64k的字符串任意一种情况的时候就会触发垃圾回收器工作,看起来很科学,不用按一段时间就调用一次,有时候会没必要,这样按需调用不是很好吗?但是如果环境中就是有这么多变量等一直存在,现在脚本如此复杂,很正常,那么结果就是垃圾回收器一直在工作,这样浏览器就没法儿玩儿了。

微软在IE7中做了调整,触发条件不再是固定的,而是动态修改的,初始值和IE6相同,如果垃圾回收器回收的内存分配量低于程序占用内存的15%,说明大部分内存不可被回收,设的垃圾回收触发条件过于敏感,这时候把临街条件翻倍,如果回收的内存高于85%,说明大部分内存早就该清理了,这时候把触发条件置回。这样就使垃圾回收工作职能了很多

2、合理的GC方案

1)、Javascript引擎基础GC方案是(simple GC):mark and sweep(标记清除),即:

  • (1)遍历所有可访问的对象。

  • (2)回收已不可访问的对象。

2)、GC的缺陷

和其他语言一样,javascript的GC策略也无法避免一个问题:GC时,停止响应其他操作,这是为了安全考虑。而Javascript的GC在100ms甚至以上,对一般的应用还好,但对于JS游戏,动画对连贯性要求比较高的应用,就麻烦了。这就是新引擎需要优化的点:避免GC造成的长时间停止响应。

3)、GC优化策略

David大叔主要介绍了2个优化方案,而这也是最主要的2个优化方案了:

(1)分代回收(Generation GC)

这个和Java回收策略思想是一致的。目的是通过区分“临时”与“持久”对象;多回收“临时对象”区(young generation),少回收“持久对象”区(tenured generation),减少每次需遍历的对象,从而减少每次GC的耗时。如图:

这里需要补充的是:对于tenured generation对象,有额外的开销:把它从young generation迁移到tenured generation,另外,如果被引用了,那引用的指向也需要修改。

(2)增量GC
这个方案的思想很简单,就是“每次处理一点,下次再处理一点,如此类推”。如图:

这种方案,虽然耗时短,但中断较多,带来了上下文切换频繁的问题。

因为每种方案都其适用场景和缺点,因此在实际应用中,会根据实际情况选择方案。

For example: when the (object/s) ratio is low, the frequency of interrupting GC execution is lower, and simple GC is lower; if a large number of objects are "survival" for a long time, the advantage of generational processing is not great.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Javascript creates classes and objects (picture and text tutorial)

Detailed interpretation of JavaScript arrow function (picture Text tutorial)

Detailed answer to this in JavaScript (Graphic tutorial)

The above is the detailed content of Comprehensive understanding of JavaScript's garbage collection mechanism_Basic knowledge. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn