Will closures cause memory leaks?

Source: Internet
Author: User

Objective

Before talking about memory leaks, look at JavaScript's garbage collection mechanism, which has an automatic garbage collection mechanism that identifies variables that are no longer in use and frees up the memory they occupy. To do this, the garbage collector will follow a fixed time interval (or the scheduled collection time in code execution). There are two commonly used methods, that is, the marked clear and the reference count.

1. Mark Clear

The most common method of garbage collection in JavaScript is tag Cleanup (mark-and-sweep). The garbage collector will tag all variables stored in memory at run time (you can use any markup method). It then removes the variables in the environment and the tags of the variables referenced by the variables in the environment. Variables that are tagged later will be considered as variables to be deleted because variables in the environment are inaccessible to those variables. Finally, the garbage collector completes the memory cleanup work, destroys those tagged values, and reclaims the memory space that they occupy.

1. Reference counting

The meaning of the reference count (reference counting) is that the trace records the number of times each value is referenced. The meaning of the reference count is the number of times each value is referenced by the tracking record. 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 added by 1. Conversely, if a variable that contains a reference to this value has another value, the number of references to the value is reduced by 1. When the number of references to this value becomes 0 o'clock, it means that there is no way to access the value again, so that it can reclaim the memory space it occupies. That way, when the garbage collector runs again next time, it frees the memory used by those values that have a zero reference count.

Netscape Navigator 3.0 is the first browser to use a reference counting strategy, but soon it encounters a serious problem, see the following example:

function problem(){    var objectA = new Object(); var objectB = new Object(); objectA.someOtherObject = objectB; objectB.anotherObject = objectA;}

Description: Objecta and OBJECTB refer to each other by their respective properties, that is, both objects have a reference count of 2, and in the implementation of the tag purge policy, both objects leave the scope after the function executes, so this mutual reference is not a problem. However, in implementations that adopt a reference counting strategy, when the function is finished, objecta and OBJECTB also indicate that they will continue to exist because their reference count will never be 0. If this function is repeated multiple calls, it will result in a large amount of memory not being recycled.

For this reason, Netscape has discarded the reference count in Navigator 4.0, but the trouble with reference counting has not been settled. IE9 Previously, some of the objects were not native JavaScript objects. For example, the objects in their BOM and Dom are implemented using C + + as COM (Component object model, Component object models) objects, and the garbage collection mechanism of COM objects is a reference counting strategy. Therefore, even though the JavaScript engine of IE is implemented using the tag purge policy, the COM objects that JavaScript accesses are still based on the reference counting policy. In other words, whenever a COM object is involved in IE, there is a circular reference problem.
Like what:

var element = document.getElementById("some_element");var myObject = new Object();myObject.element = element;element.someObject = myObject;

A circular reference is created between the DOM element and a native JavaScript object (myObject). Where the variable MyObject has a property named element pointing to the element object, and the variable element has a property called the Someobject callback MyObject. Since this circular reference exists, even if the DOM in the example is removed from the page, it will never be recycled.

WORKAROUND: Set the variable to NULL to cut off the connection between the variable and the value it previously referred to.

null;element.someObject = null;

After reading the above, I'll talk to you.

Closures do notcausing a memory leak

Because the previous versions of IE9 use different garbage collection for JScript objects and COM objects. Therefore closures in these versions of IE can cause some special problems. Specifically, if an HTML element is stored in the scope chain of the closure, it means that the element will not be destroyed see example:

function assignHandler(){    var element = document.getElementById("someElement"); element.onclick = function(){ alert(element.id); };}

The code above creates a closure that acts as an element event handler, and the closure creates a circular reference (the event is discussed in Chapter 13th). Because the anonymous function holds a reference to the active object of Assignhandler (), it causes the reference count of element to not be reduced. As long as the anonymous function exists, the reference number of element is at least 1, so that the memory it occupies will never be recycled, this is the problem of IE, so closures and memory leaks do not have a half-dime relationship.

Workaround the preface has already mentioned that a copy of the element.id is saved in a variable, thereby eliminating the loop reference to the variable in the closure and setting the element variable to null.

function assignHandler(){    var element = document.getElementById("someElement"); var id = element.id; element.onclick = function(){ alert(id); }; element = null;}

Summary: Closures do not cause a memory leak, only because the previous version of IE9 uses different garbage collection for JScript objects and COM objects, causing memory to not be recycled.
This article has done a detailed test, interested can click to view

Small episode: Send a group of links, interested can join the Exchange, Group No.: 519875573

Will closures cause memory leaks?

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.