Comprehensive understanding of Javascirpt garbage (garbage collection) Recycling mechanism _ Basics

Source: Internet
Author: User
Tags garbage collection time interval

-GC of waste recycling mechanism

JavaScript has an automatic garbage collection mechanism (Gc:garbage collecation), in other words, the execution environment is responsible for managing the memory used during code execution.

Principle: The garbage collector periodically (periodically) identifies those variables that are not being used, and then releases their memory.

The mechanism for JavaScript garbage collection is simple: Find the variables that are no longer in use, and then release the memory they occupy, but the process is not real-time because it costs more, so the garbage collector periodically executes at fixed intervals.

A variable that is no longer in use is a variable that ends the lifecycle, of course, only a local variable, and the lifecycle of the global variable will not end until the browser unloads the page. Local variables exist only during the execution of a function, in this process, the local variables are allocated space on the stack or heap to store their values, and then the variables are used in the function until the function ends, and the external function is not closed due to intrinsic function in the closure.

Let's go to the code and explain it:

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 defines two function, respectively called FN1 and fn2, when FN1 is called, enter the FN1 environment, will open up a memory storage object {name: ' Hanzichi ', age:10}, and when the call is over, out of the FN1 environment, The block memory is automatically freed by the garbage collector in the JS engine, and the object returned is pointed to by global variable B during fn2 invocation, so the block memory is not freed.

Here's the problem: which variable is useless? So the garbage collector must keep track of which variable is useless, and mark the variables that are no longer useful for future memory recovery. The policies used to mark unwanted variables may differ by implementation, typically in two ways: flag cleanup and reference counting. Reference counting is less common, and mark removal is more common.

Second, Mark Clear

The most common way of garbage collection in JS is Mark removal. When a variable enters the environment, for example, when declaring a variable in a function, it marks the variable as "entering the environment." Logically, the memory occupied by variables entering the environment can never be released, because they may be used as long as the execution stream enters the appropriate environment. When a variable leaves the environment, it is marked as "out of the environment."

function test () {
 var a = 10;//Tagged, enter environment 
 var b = 20;//marked, enter environment
}
Test ()/////////////////////////////////////// 

The garbage collector will mark all variables stored in memory at run time (and, of course, any markup method can be used). It then removes the variables in the environment and the tags (closures) of the variables referenced by the variables in the environment. Variables that are then tagged later are considered variables to be deleted because variables in the environment are already inaccessible to these variables. Finally, the garbage collector completes the memory cleanup work, destroys those tagged values, and reclaims the memory space they occupy.

So far, the JS implementations of IE, Firefox, Opera, Chrome, and Safari use all of the garbage collection policies or similar policies that are marked for elimination, except that the time intervals for garbage collections are different.

Third, reference count

Reference counting means tracking 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 that value is 1. If the same value is assigned to another variable, the number of references to that value is 1. Conversely, if a variable that contains a reference to that value gets another value, the reference number of that value is reduced by 1. When the number of references to this value changes to 0 o'clock, there is no way to access the value again, so you can reclaim the memory space it occupies. In this way, when the garbage collector next runs, it releases the memory occupied by values that have a reference number of 0.

function test () {
 var a = {};//a is 0 
 var b = A;//a's reference count plus 1, 1 
 var c =a;//a's reference count plus 1, 2
 var b ={};//a The number of references is reduced by 1 to 1
} 

Netscape Navigator3 was the first browser to use the reference counting policy, 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 above code A and B are all referred to 2,FN () after execution, two objects have left the environment, there is no problem with the Mark cleanup, but under the reference count policy because A and B are not referenced by 0, the garbage collector will not reclaim the memory, if the FN function is called in large numbers, can cause memory leaks. On IE7 and IE8, memory goes up in a straight line.

We know that some of the objects in IE are not native JS objects. For example, the memory leaks DOM and the objects in the BOM are implemented using C + + as a COM object, whereas the COM object's garbage collection mechanism uses a reference-counting policy. Therefore, even if IE's JS engine uses the Mark elimination strategy to implement, but JS accesses the COM object to still be based on the reference counting strategy. In other words, as long as the COM object is involved in IE, there is a circular reference problem.

var element = document.getElementById ("some_element");
var myObject = new Object ();
MYOBJECT.E = element;
ELEMENT.O = MyObject; 

This example creates a circular reference between a DOM element (element) and a native JS object (myObject). Where the variable MyObject has a property named element that points to the element object, and the variable element also has a property named O anaphora myobject. Because of this circular reference, even if the DOM in the example is removed from the page, it will never be reclaimed.

Look at the example above, some students feel too weak, who would do such a boring thing, in fact, we are not doing

Window.onload=function outerfunction () {
 var obj = document.getElementById ("element");
 Obj.onclick=function innerfunction () {};
}; 

This code looks fine, but obj references document.getElementById ("element") and document.getElementById ("element") The OnClick method will refer to the external environment of the German variable, naturally including obj, is not very covert ah.

Solutions

The easiest way to do this is to manually dismiss the circular reference, such as just the function

Myobject.element = null;
ELEMENT.O = null; 
Window.onload=function outerfunction () {
 var obj = document.getElementById ("element");
 Obj.onclick=function innerfunction () {};
 Obj=null;
}; 

Setting a variable to null means severing the connection between the variable and the value it previously referenced. The next time the garbage collector runs, the values are deleted and the memory they occupy is reclaimed.

Note that the ie9+ does not have a circular reference that causes a DOM memory leak problem, either Microsoft has optimized it, or the DOM's recycling method has changed

Four, memory management

1. When will the garbage collection be triggered?

The garbage collector runs periodically, and if there is a lot of memory allocated, then the recovery effort can be daunting, and determining the time interval for garbage collection becomes a worthwhile consideration. IE6 garbage collection is based on the amount of memory allocated, when there are 256 variables, 4,096 objects, 64k strings in any one situation will trigger the garbage collector to work, looks very scientific, do not have to call once a period of time, sometimes not necessary, so on-demand call is not very good? But if there are so many variables in the environment, and now the script is so complex and normal, the result is that the garbage collector is working so that the browser can't play.

Microsoft has made adjustments in the IE7, the trigger condition is no longer fixed, but dynamically modified, with the same initial value and IE6, if the garbage collector reclaims less than 15% of the memory allocated by the program, which means that most of the memory is not recoverable, and the set of garbage collection trigger conditions is too sensitive to double the street condition. If the reclaimed memory is higher than 85%, most of the memory should have been cleaned up long ago, and the trigger condition is put back. This makes the garbage collection work a lot more functional.

2, a reasonable GC scheme

1 The JavaScript engine base GC scheme is (simple GC): Mark and Sweep (Mark Cleanup), namely:

    • (1) Iterate over all accessible objects.
    • (2) Reclaim objects that have not been accessed.

2), GC defects

As with other languages, JavaScript's GC policy cannot avoid a problem: When GC, stop responding to other actions for security reasons. and JavaScript in the GC in 100ms or more, the general application is fine, but for JS games, animation for the consistency of the application of high requirements, it is troublesome. This is the point where the new engine needs to be optimized: Avoid the long stop response caused by the GC.

3), GC optimization strategy

Uncle David introduced 2 optimization programs, and this is the main 2 optimization:

(1) Generational recycling (Generation GC)

This is consistent with the idea of Java recycling strategy. The goal is to reduce the time consuming per GC by distinguishing between "temporary" and "persistent" objects, by recycling the "temporary objects" area (young Generation), by recycling less the persistent objects area (tenured generation), and by reducing the number of objects that need to be traversed each time. As shown in figure:

Here's what you need to add: for tenured generation objects, there is an extra overhead: migrating it from young generation to tenured generation, and if referenced, the reference point needs to be modified.

(2) Incremental GC
The idea of this program is simple: "deal with a little bit at a time, then deal with it a little bit, so on." As shown in figure:

This kind of scheme, although the time is short, but the interruption is many, has brought the problem which the context switch is frequent.

Because each scenario is suitable for scenarios and shortcomings, in practical applications, the scheme will be chosen according to the actual situation.

For example, when the low (object/s) ratio, the frequency of interrupt execution GC, simple GC lower, if a large number of objects are long-term "survival", the advantage of generational processing is not small.

The above comprehensive understanding of the javascirpt garbage (garbage collection) recycling mechanism is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.