JavaScript garbage collection mechanism analysis _javascript skills

Source: Internet
Author: User
Tags closure

In the company often hear Daniel talk about memory leak God horse, often amazing unceasingly, recent energy mainly used in the web development, read the "JavaScript Advanced Program Design" (the title is very scary, the actual author writes particularly good, To understand the JavaScript garbage collection mechanism, the memory leak has a certain understanding.

Like C # and Java, JavaScript has an automatic garbage collection mechanism, which means that the execution environment is responsible for managing the memory used in the execution of the code, and that there is no need to consider the memory allocation and garbage recovery issues during the development process. 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 always, because it is expensive, so the garbage collector periodically executes at a fixed interval.

Variable life cycle

Some students read the above will ask, what is no longer used variables? 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 use these variables in the function until the end of the function (in the closure due to internal function, the external function is not the end, understand the closure can see JavaScript scope chain, what JavaScript closures are.

Once the function is finished, local variables are not necessary and can be freed of the memory they occupy. Cat and a very simple job, why is there a lot of overhead? This is just the tip of the iceberg of garbage collection, just like the closure of the just mentioned, seemingly function is over, in fact, the garbage collector must swim the variable, that variable is useless, for the variables no longer useful to mark for future recycling. There are a number of strategies for tagging useless, and there are two common ways

Mark Clear (Mark and sweep)

This is the most common form of garbage collection in JavaScript, when a variable enters the execution environment, such as declaring a variable in a function, and the garbage collector marks it as "into the environment", marking it as "leaving the environment" when the variable leaves the environment (the function ends). As for how to mark there are many ways, such as the reversal of special bits, maintain a list, and so on, it is not important, it is important to use what strategy, in principle, can not release the memory of the variables into the environment, they can be called at any time.

The garbage collector marks all variables stored in memory at run time, then remove the variables in the environment and the variables referenced by the variables in the environment (closures), and after those completion there are still tags that are to be deleted, because the variables in the environment are already inaccessible to these variables. The garbage collector then encounters the space occupied by these tagged variable machines.

Most browsers use this method for garbage collection, the difference is how to mark and garbage collection interval, only the lower version of IE, as expected, is IE ...

Reference count (reference counting)

Memory leaks often occur in lower versions of IE, many times because they are garbage collected using reference counting. The strategy for reference counting is to track the number of times each value is used. When a variable is declared and a reference type is assigned to the variable, the reference number of that value is 1, and if the value of the variable becomes another one, then the number of references is reduced by 1, and when the number of references to this value becomes 0, This means that no variables are being used, and this value cannot be accessed, so you can reclaim the space it occupies so that the garbage collector cleans up the space that the value of the reference number 0 takes up at run time.

It's a good way to look, why is it very rare for browsers to use, and will it also bring memory leaks? This is mainly because there is no way to solve the circular reference problem. For example, object A has a property that points to object B, and object B has a property that points to object A, so that each reference

Copy Code code as follows:

function Test () {
var a={};
var b={};
A.prop=b;
B.prop=a;
}

So the citations of A and B are all 2, even after the execution of Test (), two objects have left the environment, there is no problem with the policy of marking the purge, but it is clear to leave the environment, but not under the reference count policy, because the two objects are still referenced 2, not 0. So its footprint will not be cleaned up, if this function is called multiple times, this will continue to have space will not be recycled, resulting in memory leaks.

In IE, although JavaScript objects are garbage collected by means of marked scavenging, the BOM and Dom objects recycle garbage by reference counting, which means that there is a circular reference problem as long as the BOM and Dom are involved. Look at the example above, some students feel too weak, who would do such a boring thing, in fact, we are not doing

Copy Code code as follows:

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

Copy Code code as follows:

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

When do I trigger a garbage collection?

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 garbage collection work a lot of functions.

As with C #, Java we can invoke the garbage collector manually, but because it consumes a lot of resources, and we call the manual is not more accurate than the browser, it is not recommended to call garbage collection manually.

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.