search
HomeWeb Front-endJS TutorialWill closures cause memory leaks?

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; 
}

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;

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;

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); 
    }; 
}

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; 
}

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.

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.