The principle analysis of JavaScript garbage collection mechanism _javascript skill

Source: Internet
Author: User
Tags garbage collection object model

Front.

JavaScript has an automated garbage collection mechanism, which is responsible for managing the memory used during code execution. When writing JavaScript programs, developers no longer have to worry about memory usage issues, the allocation of required memory, and the recycling of unwanted memory fully automate management. The JavaScript garbage collection mechanism is described in detail below

Principle

The principle of the garbage collection mechanism is simple: find the variables that are no longer in use, and then release the memory they occupy, which is periodically performed by the garbage collector at regular intervals, or scheduled collection times in code execution

Local variables exist only during the execution of a function. In this process, the local variables are allocated space on the stack (or heap) memory to store their values. These variables are then used in the function until the function execution ends. At this point, there is no need for local variables to exist. As a result, their memory can be freed for future use. In this case, it is easy to determine whether the variable is still necessary to exist, but not in all cases it is so easy to draw a conclusion

The garbage collector must keep track of which variable is useful and which variable is useless, marking a variable that is no longer useful for future recall of the memory it occupies. A policy that identifies a useless variable usually has two types of tag cleanup and reference counting

Mark Clear

The most common method of garbage collection in JavaScript is tag Cleanup (mark-and-sweep), which marks the variable as ' into the environment ' when the variable enters the environment (for example, declaring a variable in a function). 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. And when the variable leaves the environment, it marks it as ' leave the environment '

You can tag variables in any way. For example, you can track which variable has changed by flipping a particular bit to record when a variable enters the environment, or by using a ' Enter the environment ' variable list and a list of variables to leave the environment. In the final analysis, it doesn't matter how you label variables, it's what strategy you take

The garbage collector marks all variables stored in memory at run time. It then removes the variables in the environment and the tags 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, destroys those tagged values, and reclaims the memory space they occupy

Most browser implementations use a tag-purge garbage collection strategy, except that the time for garbage collection is different

Reference count

Another less common garbage collection policy is called reference counting (reference counting)

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, and if the same value is assigned to another variable, the number of references to that value is added to 1. Conversely, if a variable that contains a reference to this value gets another value, the reference number of that value is reduced by 1, and when the reference number of this value is 0 o'clock, there is no way to access the value again, so the memory space it occupies can be recycled back. This way, when the garbage collector next runs, it frees up the memory that the value of the reference count is 0

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

function problem () {
 var objecta = new Object ();
 var OBJECTB = new Object ();
 Objecta.someotherobject = OBJECTB;
 Objectb.anotherobject = objecta;
}

In this example, Objecta and OBJECTB are referred to each other by their respective attributes, both of which refer to the number of 2. In an implementation that uses the tag cleanup policy, since the function was executed, both objects have left the scope, so this mutual reference is not an issue. However, in the implementation of the reference counting policy, when the function completes, objecta and OBJECTB will continue to exist, because they will never be referenced more than 0 times. If this function is repeated multiple times, it can cause a lot of memory to be recycled

Some of the objects in IE are not native JavaScript objects, for example, the objects in their BOM and Dom are implemented using C + + as a COM (Component Object model) object, and the garbage collection mechanism of COM object is to use reference counting strategy. Therefore, even though IE's JavaScript engine is implemented using a tag-purge policy, the COM objects that JavaScript accesses are still based on the reference-counting policy. In other words, as long as the COM object is involved in IE, there will be a circular reference problem

var element = document.getElementById (' some_element ');
var myObject = new Object ();
Myobject.element = element;
Element.someobject = MyObject;

This example creates a circular reference between a DOM element (element) and a native JavaScript 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 Someobject that points to MyObject. Because of this circular reference, even if the DOM in the example is removed from the page, it will never be recycled

To avoid circular references like this, it is best to manually disconnect between native JavaScript and DOM elements without using them

Myobject.element = 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, it deletes these values and reclaims the memory they occupy

To solve this problem, IE9 transforms the BOM and Dom objects into real JavaScript objects

Performance Issues

The garbage collector runs periodically, and if the amount of memory allocated to a variable is significant, the amount of recovery effort is significant. In this case, determining the garbage collection interval is a very important issue

The garbage collector of IE is based on the amount of memory allocated. Specifically, 256 variables, 4,096 objects (or array) literals and arrays of elements (slot) or 64KB strings. If any of these thresholds are reached, the garbage collector will run

The problem with this implementation is that if a script contains so many variables, the script is likely to retain so many variables throughout its lifecycle. As a result, the garbage collector has to run frequently. As a result, the resulting severity problem prompted IE7 to rewrite its garbage collection routines

The garbage collection routines of the IE7 JavaScript engine change the way they work: the variables that trigger garbage collection, the values of literal and array elements are adjusted to dynamic corrections. The critical values in the IE7 are initially equal to the IE6. If the garbage collection routine reclaims less than 15% memory allocations, the critical values of the variables, literals, and array elements are doubled. If the routine reclaims 85% of the memory allocations, resets the various critical values back to the default values. This greatly increases the performance of IE when running pages that contain a lot of javascript

In fact, the garbage collection process can be triggered in some browsers. In IE, call window. The CollectGarbage () method performs the garbage collection immediately

Memory management

The main problem with JavaScript with garbage collection is that the amount of available memory allocated to a Web browser is typically less than that allocated to a desktop application, in order to prevent a Web page running JavaScript from draining all system memory and causing the system to crash. Memory restriction issues affect not only the allocation of memory to variables, but also the call stack and the number of statements that can be executed concurrently in one thread

Therefore, ensuring that the least amount of memory is used allows the page to achieve better performance. The best way to optimize memory usage is to save only the necessary data for the code in execution. Once the data is no longer useful, it is best to release its reference by setting its value to null, which is called a dereference (dereferencing). This practice applies to the properties of most global variables and global objects, and local variables are automatically lifted when they leave the execution environment

function Createperson (name) {
 var Localperson = new Object ();
 Localperson.name = name;
 return localperson;
}
var Globalperson = Createperson (' test ');
Globalperson = null;

Note, however, that lifting a reference to a value does not automatically reclaim the memory occupied by the value. The real effect of the dereference is to leave the value out of the execution environment so that the garbage collector can recycle it the next time it runs

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, if there are questions you can message exchange, but also hope that a lot of support cloud Habitat community!

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.