JavaScript -- Item28 garbage collection mechanism and memory management that you don't know

Source: Internet
Author: User

JavaScript -- Item28 garbage collection mechanism and memory management that you don't know
1. Garbage collection mechanism-GC

Javascript has an automatic Garbage collection mechanism (GC: Garbage Collecation), that is, the execution environment is responsible for managing the memory used during code execution.

Principle: The spam collector willRegular (periodic)Find out the variables that are not in use and then release their memory.

The mechanism of JavaScript garbage collection is very simple: Find out the variables that are no longer used, and then release the memory occupied by them, but this process is not real-time. Because of its large overhead, the garbage collector will followPeriodic execution at fixed intervals.

A variable that is no longer used is the variable whose life cycle ends. Of course, it may only be a local variable. the life cycle of a global variable ends only when the browser uninstalls the page. Local variables only exist during function execution. In this process, local variables are allocated space on the stack or stack to store their values, then, use these variables in the function until the function ends. External functions cannot be ended due to internal functions in the closure.

Let's go to the Code Description:

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 look at how the code is executed. First, two functions are defined, namely fn1 and fn2. When fn1 is called, The fn1 environment opens up a memory storage object.{name: 'hanzichi', age: 10}When the fn1 environment exists after the call is completed, the block of memory will be automatically released by the garbage collector in the js engine. During the fn2 call process, the returned object is pointed by global variable B, so the block memory is not released.

Here the problem arises: Which variable is useless? Therefore, the garbage collector must track which variable is useless and Mark variables that are no longer useful for future memory recovery. The policies for marking useless variables may vary by implementation. Generally, there are two implementation methods: Mark clearing and reference counting. Reference count is not commonly used, and Mark clearing is commonly used.

2. mark and clear

The most common method of garbage collection in js is to mark and clear. When a variable enters the environment, for example, when a variable is declared in the function, it is marked as"Enter the environment". Logically, the memory occupied by variables entering the environment cannot be released, because they may be used as long as the execution stream enters the corresponding environment. When the variable leaves the environment, it is marked as"Exit Environment".

Function test () {var a = 10; // marked to enter the environment var B = 20; // marked to enter the environment} test (); // after execution, a and B are marked out of the environment and recycled.

When the garbage collector is running, it will mark all variables stored in the memory (of course, any marking method can be used ). Then, it removes the environment variables and the variables referenced by the environment variables (Closure). The variables marked after this are considered as the variables to be deleted, because they are no longer accessible to environment variables. Finally, the garbage collector clears the memory, destroys the marked values, and recycles the memory space they occupy.

So far, JavaScript implementations of IE, Firefox, Opera, Chrome, and Safari use garbage collection policies or similar policies that Mark cleanup, except that the interval of garbage collection is different.

3. Reference count

The reference count indicates 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 times this value is referenced is 1. If the same value is assigned to another variable, the number of times the value is referenced increases by 1. On the contrary, if another value is obtained for the variable that contains the reference to this value, the number of references to this value is reduced by 1. When the number of references for this value changes to 0, it indicates that there is no way to access this value, so the occupied memory space can be recycled back. In this way, when the Garbage Collector runs again next time, it will release the memory occupied by the value with 0 references.

Function test () {var a = {}; // the number of times a is referenced is 0 var B = a; // the number of times a is referenced is increased by 1 to 1 var c =; // Add 1 to the number of references of a, which is 2 var B = {}; // The number of references of a minus 1, which is 1}

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

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

The numbers of references for code a and B above are both 2. After fn () is executed, both objects have left the environment and there is no problem in the mark clearing mode, however, in the reference counting policy, the memory will not be reclaimed by the garbage collector because the reference times of a and B are not 0. If the fn function is called in large quantitiesMemory leakage. On IE7 and IE8, the memory goes up.

We know that some objects in IE are not native js objects. For exampleMemory leakageThe objects in DOM and BOM are implemented in the form of COM objects, while the garbage collection mechanism of COM objects adopts the reference counting policy. Therefore, even ifThe js engine of IE adopts the mark clearing policy.But js accessesCOM object is still based on reference counting Policy. In other words, as long as Internet Explorer involves COM objects, circular references may occur.

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 and a native js object (myObject. The variable myObject has an attribute named "element" pointing to the element object, and the variable element also has an attribute named "o" pointing to the myObject. Because of this circular reference, even if the DOM in the example is removed from the page, it will never be recycled.

Looking at the example above, some people think it is too weak. Who will do this boring thing? Are we actually doing it?

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

This code looks okay, but obj referencesdocument.getElementById(“element”), Anddocument.getElementById(“element”)The onclick method of references the Sino-German variables in the external environment. Naturally, it also includes obj. Is it very concealed.

Solution

The simplest way is to manually remove circular references. For example, the function just now can.

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

Setting the variable to null means that the connection between the variable and its previously referenced value is cut off. When the Garbage Collector runs the next time, it deletes these values and recycles the memory they occupy.

It should be noted that IE9 + does not cause Dom Memory leakage due to circular references. It may be because Microsoft has optimized the Dom or the Dom recycling method has changed.

4. Memory Management

1. When will garbage collection be triggered?

The garbage collector runs cyclically. If a large amount of memory is allocated, the garbage collection will be very difficult. Determining the garbage collection interval becomes a question worth thinking about. The garbage collection function of IE6 runs based on the memory allocation. When there are 256 variables, 4096 objects, and 64 K strings in the environment, the garbage collection task is triggered, it looks scientific. You don't have to call it once in a period of time. Sometimes it's unnecessary. Isn't it good to call it as needed? However, if there are so many variables in the environment, and the script is so complicated and normal, the result is that the garbage collector is always working, so that the browser cannot play with it.

Microsoft made adjustments in IE7, and the trigger condition is not fixed, but dynamic. The initial value is the same as that of IE6. If the memory allocated by the garbage collector is less than 15% of the memory occupied by the program, this indicates that most of the memory cannot be recycled, and the trigger conditions for garbage collection are too sensitive. In this case, the off-street conditions are doubled. If the collected memory is higher than 85%, it indicates that most of the memory should have been cleared up long ago, at this time, the trigger condition is set back. In this way, the garbage collection function is greatly improved.

2. Reasonable GC Solution

The basic GC solution of the Javascript engine is (simple GC): mark and sweep (mark clearing), that is:

(1) traverse all accessible objects.

(2) reclaim inaccessible objects.

GC Defects

Like other languages, the GC policy of javascript cannot avoid a problem: when GC is performed, it stops responding to other operations for security consideration. The GC of Javascript is at least MS, which is good for general applications. However, for JS games, it is troublesome to apply animations with high consistency requirements. This is the point that the new engine needs to be optimized: To avoid GC-caused long-time stop response.

GC Optimization Strategy

Uncle David mainly introduced two optimization schemes, which are also the two most important optimization schemes:

(1) Generation GC)

This is consistent with the Java recycling strategy. The purpose is to distinguish between "temporary" and "persistent" objects. The "temporary object" area (young generation) is recycled more, and the "Persistent Object" area (tenured generation) is recycled less ), reduce the objects to be traversed each time, thus reducing the time consumed by each GC.

The additional overhead for tenured generation objects is: migrating it from young generation to tenured generation. In addition, if it is referenced, the reference point also needs to be modified. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Character/character = "write image description here" src = "http://www.bkjia.com/uploads/allimg/151111/050FQ262-1.png" title = "character? + "Warning ^)] + vl tease 'Warning-warning garbage disposal" http://www.bkjia.com/kf/ware/Java/ "target =" _ blank "class =" keylink "> Javascript garbage collection analysis closure Collection & garbage collection mechanism

 

Related Article

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.