Analysis of JavaScript garbage collection mechanism

Source: Internet
Author: User

When companies often hear discussions about memory leaks, everyone is amazed. Recently, my focus has been on Web development, I read "JavaScript advanced programming" (the title is very good, but the actual author wrote it very well, from a simple perspective) to understand the JavaScript garbage collection mechanism, and have a certain understanding of Memory leakage.

Like C # and Java, JavaScript has an automatic garbage collection mechanism. That is to say, the execution environment is responsible for managing the memory used during code execution, in the development process, you do not need to consider the memory allocation and useless memory recovery issues. 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. However, this process is not always due to its high overhead, therefore, the garbage collector periodically runs at a fixed interval.

Variable Lifecycle

After reading the above, some people will ask, what is a variable that is no longer used? 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 end due to internal functions in the closure. To understand the closure, you can look at the JavaScript scope chain, javaScript closure ).

Once the function is complete, local variables are not necessary to release the memory they occupy. Why are cats and cats very productive in their simple work? This is just the tip of the iceberg of garbage collection. Just like the closure mentioned above, it seems that the function is over. Actually, it is not. The Garbage Collector must swim with the variable, and the variable is useless, mark variables that are no longer useful for future recycling. There are many methods to mark useless policies. There are two common methods.

Mark and sweep)

This is the most common garbage collection method in JavaScript. When a variable enters the execution environment, such as declaring a variable in a function, the garbage collector marks it as "entering the environment ", when a variable leaves the environment (function execution ends), it is marked as "out of the environment ". There are many methods for marking, such as reversing the special bit and maintaining a list. These are not important. What is the most important is what strategy to use, in principle, the memory occupied by variables entering the environment cannot be released, and they may be called at any time.

The garbage collector will mark all variables stored in the memory at runtime, and then remove the environment variables and the variables referenced by the environment variables (closures ), after the completion, the variables marked to be deleted are still marked, because the variables in the environment are no longer accessible to these variables, and the garbage collector will meet the space occupied by these labeled variable machines.

Most browsers use this method for garbage collection. The difference is how to mark and separate garbage collection. Only earlier versions of IE, as expected, are Internet Explorer...

Reference counting)

In earlier versions of IE, memory leakage often occurs. In many cases, it is because it adopts the reference counting method for garbage collection. The reference count policy 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 count of this value is increased by 1, if the value of this variable is changed to another one, the number of worthy references is reduced by 1. When the number of references of this value is changed to 0, it indicates that no variable is in use, this value cannot be accessed, so the space occupied by it can be recycled. In this way, the garbage collector will clear the space occupied by the value with 0 references during running.

It looks good. Why does a few browsers still cause memory leakage? It is mainly because this method cannot solve the problem of circular reference. For example, object A has an attribute pointing to object B, and object B also has an attribute pointing to object A, so that they reference each other.

Copy codeThe Code is as follows:
Function test (){
Var a = {};
Var B = {};
A. prop = B;
B. prop =;
}

In this way, the number of references for a and B is 2. Even after the test () execution is complete, both objects have left the environment and there is no problem in the marked clearing policy, if you leave the environment, it will be cleared, but it will not work under the reference counting policy, because the number of references of the two objects is still 2 and will not change to 0, so the occupied space will not be cleared, if this function is called multiple times, the space will not be recycled, resulting in Memory leakage.

In IE, although JavaScript objects are marked and cleared for garbage collection, BOM and DOM objects collect garbage by reference counting, that is to say, as long as the BOM and DOM are involved, the circular reference problem will occur. Looking at the example above, some people think it is too weak. Who will do this boring thing? Are we actually doing it?

Copy codeThe Code is as follows:
Window. onload = function outerFunction (){
Var obj = document. getElementById ("element ");
Obj. onclick = function innerFunction (){};
};

This code looks okay, but obj references document. getElementById ("element"), while document. the onclick method of getElementById ("element") references the Sino-German variables in the external environment, including obj. Is it hidden.

Solution

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

Copy codeThe Code is as follows:
Window. onload = function outerFunction (){
Var obj = document. getElementById ("element ");
Obj. onclick = function innerFunction (){};
Obj = null;
};

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

Like C # and Java, We can manually call the garbage collection program. However, because it consumes a lot of resources, and the Manual calls are not more accurate than the browser's judgment, therefore, it is not recommended to manually call garbage collection.

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.