Home > Web Front-end > JS Tutorial > Will closures cause memory leaks?

Will closures cause memory leaks?

高洛峰
Release: 2016-11-01 11:37:04
Original
1628 people have browsed it

Foreword

Before talking about the issue of memory leaks, let’s take a look at JavaScript’s garbage collection mechanism. JavaScript has an automatic garbage collection mechanism, which is to find variables that are no longer used and then release the memory they occupy. To do this, the garbage collector works at fixed intervals (or scheduled collection times during code execution). There are two commonly used methods, namely clear marking and reference counting.

1. Mark Sweep

The most commonly used garbage collection method in JavaScript is mark-and-sweep. The garbage collector will mark all variables stored in memory when it runs (any marking method can be used). Then, it removes the tags of variables in the environment and variables referenced by variables in the environment. Variables that are marked after this will be regarded as variables to be deleted because variables in the environment can no longer access these variables. Finally, the garbage collector completes the memory cleanup work, destroying those marked values ​​and reclaiming the memory space they occupy.

2. Reference counting

The meaning of reference counting is to track and record 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 this value is 1. If the same value is assigned to another variable, the reference count of the value is increased by 1. Conversely, if the variable containing a reference to this value obtains another value, the number of references to this value is decremented by one. When the number of references to this value becomes 0, it means that there is no way to access this value anymore, so the memory space it occupies can be reclaimed. This way, the next time the garbage collector runs, it will free the memory occupied by values ​​with zero references.

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

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

Explanation: objectA and objectB refer to each other through their respective attributes, that is, this The reference count of both objects is 2. In an implementation using the mark-and-sweep strategy, since both objects leave the scope after the function is executed, this mutual reference is not a problem. However, in an implementation using a reference counting strategy, objectA and objectB will continue to exist after the function is executed, because their number of references will never be 0. If this function is called multiple times, a large amount of memory will not be recycled.

For this reason, Netscape gave up the reference counting method in Navigator 4.0. However, the trouble caused by reference counting did not end there. Some objects in IE before 9 were not native JavaScript objects. For example, the objects in its BOM and DOM are implemented in the form of COM (Component Object Model) objects using C++, and the garbage collection mechanism of COM objects uses a reference counting strategy. Therefore, even though IE's JavaScript engine is implemented using the mark-and-sweep strategy, the COM objects accessed by JavaScript are still based on the reference counting strategy. In other words, whenever COM objects are involved in IE, there will be a circular reference problem.

For example:

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

A circular reference is created between a DOM element (element) and a native JavaScript object (myObject). Among them, 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 refers back to myObject. Because of this circular reference, even if the DOM in the example is removed from the page, it will never be recycled.

Solution: Set the variable to null to sever the connection between the variable and the value it previously referenced.

myObject.element = null; 
 
element.someObject = null;
Copy after login

After reading the above content, let me talk about the topic.

Closures will not cause memory leaks

Because versions before IE9 use different garbage collection for JScript objects and COM objects. Closures therefore cause some special problems in these versions of IE. Specifically, if an HTML element is stored in the closure's scope chain, it means that the element cannot be destroyed. Please see the example:

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

The above code creates a closure that acts as an event handler for the element element. This closure creates a circular reference. Since the anonymous function saves a reference to the active object of assignHandler(), it will result in the inability to reduce the number of references to element. As long as the anonymous function exists, the reference number of element is at least 1, so the memory it occupies will never be recycled

The solution has been mentioned in the preface, save a copy of element.id in a variable, thereby eliminating The circular reference to the variable in the closure also sets the element variable to null.

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

Summary: Closures do not cause memory leaks, but because versions before IE9 use different garbage collection for JScript objects and COM objects, the memory cannot be recycled. This is a problem with IE, so closures and memory Leakage doesn't matter.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template