Home Web Front-end JS Tutorial A detailed discussion of JavaScript memory leaks_javascript skills

A detailed discussion of JavaScript memory leaks_javascript skills

May 16, 2016 pm 04:31 PM
javascript memory leak

1. What is a closure and the scope chain involved in the closure will not be discussed here.

2. JavaScript garbage collection mechanism

JavaScript does not need to manually release memory, it uses an automatic garbage collection mechanism (garbage collection). When an object is useless, that is, when no variable in the program refers to the object, the variable will be released from memory.

Copy code The code is as follows:

var s = [1, 2,3];
var s = null;
//This way the original array [1,2,3] will be released.

3. Circular reference

Three objects A, B, C

AàBàC: A certain attribute of A refers to B, and C is also referenced by an attribute of B. If A is cleared, then B and C are also released.

AàBàCàB: Here a certain attribute of C is added to reference the B object. If this is to clear A, then B and C will not be released because a circular reference is generated between B and C.

Copy code The code is as follows:

var a = {};
a.pro = { a:100 };
a.pro.pro = { b:100 };
a = null ;
//In this case, {a:100} and {b:100} are also released at the same time.
                                                                      var obj = {};
Obj.pro = { a : 100 };
Obj.pro.pro = { b : 200 };
var two = obj.pro.pro;
Obj = null;
//In this case {b:200} will not be released, but {a:100} will be released.

4. Circular references and closures

Copy code The code is as follows:
function outer(){
var obj = {};
function inner(){
//The obj object is referenced here
}
         obj.inner = inner;
}

This is an extremely hidden circular reference. When outer is called once, two objects, obj and inner, will be created inside it. The inner property of obj refers to inner; similarly, inner also refers to obj. This is because obj is still in the closed environment of innerFun. To be precise, this It's due to JavaScript's unique "scope chain".

Therefore, closures are very easy to create circular references. Fortunately, JavaScript can handle such circular references very well.

5. Memory leak in IE

There are several types of memory leaks in IE, and there are detailed explanations here (

http://msdn.microsoft.com/en-us/library/bb250448.aspx).

Only one of them is discussed here, namely the memory leak caused by circular reference, because this is the most common situation.

When there is a circular reference between a DOM element or an ActiveX object and a normal JavaScript object, IE has special difficulties in releasing such variables. It is best to manually cut off the circular reference. This bug has been fixed in IE 7 (

http://www.quirksmode.org/blog/archives/2006/04/ie_7_and_javasc.html).

“IE 6 suffered from memory leaks when a circular reference between several objects, among which at least one DOM node, was created. This problem has been solved in IE 7. ”

If in the above example (point 4) obj refers not to a JavaScript Function object (inner), but to an ActiveX object or Dom element, the circular reference formed in IE cannot be released.

Copy code The code is as follows:

Function init(){
        var elem = document.getElementByid( 'id' );
          elem.onclick = function(){
alert('rain-man');
//The elem element
is referenced here         };
}

Elem refers to its click event listening function, which also refers back to the elem element through its scope chain. In this way, these circular references will not be released even if you leave the current page in IE.

6. Solution

The basic method is to manually clear this circular reference. Here is a very simple example. In actual application, you can build an addEvent() function yourself and clear all event bindings on the unload event of the window.

Copy code The code is as follows:

function outer(){
         var one = document.getElementById( 'one' );
         one.onclick = function(){};
}
​ window.onunload = function(){
         var one = document.getElementById( 'one' );
         one.onclick = null;
};

Other methods (by: Douglas Crockford)

Copy code The code is as follows:

/**
* Traverse an element node and all its descendant elements
*
* @param Elem node The element node to be cleared
* @param function func The function for processing
*
​*/
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
         walkTheDOM(node, func);
Node = node.nextSibling;
}
}
/**
* Clear all references to dom nodes to prevent memory leaks
*
* @param Elem node The element node to be cleared
*
​*/
function purgeEventHandlers(node) {
walkTheDOM(node, function (e) {
for (var n in e) {                                     If (typeof e[n] ===
                      'function') {
                  e[n] = null;
            }
}
});

The above is the relevant content and solutions for JavaScript memory leaks. Friends in need can refer to it

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Go memory leak tracking: Go pprof practical guide Go memory leak tracking: Go pprof practical guide Apr 08, 2024 am 10:57 AM

The pprof tool can be used to analyze the memory usage of Go applications and detect memory leaks. It provides memory profile generation, memory leak identification and real-time analysis capabilities. Generate a memory snapshot by using pprof.Parse and identify the data structures with the most memory allocations using the pprof-allocspace command. At the same time, pprof supports real-time analysis and provides endpoints to remotely access memory usage information.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Solve the memory leak problem caused by closures Solve the memory leak problem caused by closures Feb 18, 2024 pm 03:20 PM

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

How to detect memory leaks using Valgrind? How to detect memory leaks using Valgrind? Jun 05, 2024 am 11:53 AM

Valgrind detects memory leaks and errors by simulating memory allocation and deallocation. To use it, follow these steps: Install Valgrind: Download and install the version for your operating system from the official website. Compile the program: Compile the program using Valgrind flags (such as gcc-g-omyprogrammyprogram.c-lstdc++). Analyze the program: Use the valgrind--leak-check=fullmyprogram command to analyze the compiled program. Check the output: Valgrind will generate a report after the program execution, showing memory leaks and error messages.

How to avoid memory leaks in Golang technical performance optimization? How to avoid memory leaks in Golang technical performance optimization? Jun 04, 2024 pm 12:27 PM

Memory leaks can cause Go program memory to continuously increase by: closing resources that are no longer in use, such as files, network connections, and database connections. Use weak references to prevent memory leaks and target objects for garbage collection when they are no longer strongly referenced. Using go coroutine, the coroutine stack memory will be automatically released when exiting to avoid memory leaks.

Debugging techniques for memory leaks in C++ Debugging techniques for memory leaks in C++ Jun 05, 2024 pm 10:19 PM

A memory leak in C++ means that the program allocates memory but forgets to release it, causing the memory to not be reused. Debugging techniques include using debuggers (such as Valgrind, GDB), inserting assertions, and using memory leak detector libraries (such as Boost.LeakDetector, MemorySanitizer). It demonstrates the use of Valgrind to detect memory leaks through practical cases, and proposes best practices to avoid memory leaks, including: always releasing allocated memory, using smart pointers, using memory management libraries, and performing regular memory checks.

How to effectively avoid memory leaks in closures? How to effectively avoid memory leaks in closures? Jan 13, 2024 pm 12:46 PM

How to prevent memory leaks in closures? Closure is one of the most powerful features in JavaScript, which enables nesting of functions and encapsulation of data. However, closures are also prone to memory leaks, especially when dealing with asynchronous and timers. This article explains how to prevent memory leaks in closures and provides specific code examples. Memory leaks usually occur when an object is no longer needed but the memory it occupies cannot be released for some reason. In a closure, when a function refers to external variables, and these variables

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles