Details about js Memory leakage

Source: Internet
Author: User

Memory leakage means that a piece of allocated memory can neither be used nor recycled until the browser process ends. In C ++, memory leakage is often caused by manual memory management. Currently, popular languages such as C # and Java use the automatic garbage collection method to manage memory. Normally, there will be almost no memory leakage. The browser also uses the automatic garbage collection method to manage memory. However, memory leakage may occur due to a bug in the browser garbage collection method.

1. When an element on the page is removed or replaced, if the event bound to the element is still not removed, it will not be properly handled in IE. In this case, manually remove the event first, otherwise, memory leakage may occur.
Copy codeThe Code is as follows:
<Div id = "myDiv">
<Input type = "button" value = "Click me" id = "myBtn">
</Div>
<Script type = "text/javascript">
Var btn = document. getElementById ("myBtn ");
Btn. onclick = function (){
Document. getElementById ("myDiv"). innerHTML = "Processing ...";
}
</Script>

Should be changed to the following
Copy codeThe Code is as follows:
<Div id = "myDiv">
<Input type = "button" value = "Click me" id = "myBtn">
</Div>
<Script type = "text/javascript">
Var btn = document. getElementById ("myBtn ");
Btn. onclick = function (){
Btn. onclick = null;
Document. getElementById ("myDiv"). innerHTML = "Processing ...";
}
</Script>

Or use event delegation.
Copy codeThe Code is as follows:
<Div id = "myDiv">
<Input type = "button" value = "Click me" id = "myBtn">
</Div>
<Script type = "text/javascript">
Document. onclick = function (event ){
Event = event | window. event;
If(event.tar get. id = "myBtn "){
Document. getElementById ("myDiv"). innerHTML = "Processing ...";
}
}
</Script>

2,
Copy codeThe Code is as follows:
Var a = document. getElementById ("# xx ");
Var B = document. getElementById ("# xxx ");
A. r = B;
B. r =;

Copy codeThe Code is as follows:
Var a = document. getElementById ("# xx ");
A. r =;

For pure ECMAScript objects, as long as no other object references objects a and B, that is, they are only referenced between each other, they will still be identified and processed by the garbage collection system. However, in Internet Explorer, if any object in the circular reference is a DOM node or ActiveX object, the garbage collection system will not find that the circular relationships between them are isolated from other objects in the system and release them. Eventually they will be stored in the memory until the browser is closed.
3,
Copy codeThe Code is as follows:
Var elem = document. getElementById ('test ');
Elem. addEventListener ('click', function (){
Alert ('You clicked' + elem. tagName );
});

This code registers an anonymous function as a click event handler for a DOM node. The function references a DOM object elem and forms a closure. This will generate a circular reference, namely: DOM-> closure-> DOM-> closure... the DOM object will not be released before the closure is released, and the closure exists as the event handler function of the DOM object, so the closure will not be released before the DOM object is released, even if the DOM object is deleted in the DOM tree, because of this circular reference, neither the DOM object nor the closure will be released. The following method can be used to avoid Memory leakage:
Copy codeThe Code is as follows:
Var elem = document. getElementById ('test ');
Elem. addEventListener ('click', function (){
Alert ('You clicked' + this. tagName); // The elem variable is no longer directly referenced.
});

4,
Copy codeThe Code is as follows:
Function bindEvent ()
{
Var obj = document. createElement ("XXX ");
Obj. onclick = function (){
// Even if it's a empty function
}
}

Closure is very easy to construct circular references. If a function object that constitutes a closure is assigned, for example, an event processor of a DOM node, and a reference to this node is assigned to an activity (or variable) in the scope of the function object) object.
DOM_Node.onevent-<function_object. [[scope]-<scope_chain-<Activation_object.nodeRef-<DOM_Node.

It is easy to form such a circular reference, and browsing a website containing similar circular reference code (usually in every page of the website) will consume a lot (or even all) system memory.
Solution: Define the event processing function externally and remove the closure.
Copy codeThe Code is as follows:
Function bindEvent ()
{
Var obj = document. createElement ("XXX ");
Obj. onclick = onclickHandler;
}
Function onclickHandler (){
// Do something
}

Alternatively, you can delete references to dom in external functions that define event processing functions (in addition to the reference in the JavaScript authoritative guide, useless attributes in the closure can be deleted in the scope, to reduce memory consumption .)
Copy codeThe Code is as follows:
Function bindEvent ()
{
Var obj = document. createElement ("XXX ");
Obj. onclick = function (){
// Even if it's a empty function
}
Obj = null;
}

5,
Copy codeThe Code is as follows:
A = {p: {x: 1 }};
B = a. p;
Delete a. p;

After executing this code, B. the value of x is still 1. because deleted property references still exist, some implementations of JavaScript may cause memory leakage due to this type of less rigorous code. Therefore, when destroying objects, You need to traverse the attributes and delete them in sequence.
6. Automatic Type Packing Conversion
Don't believe it. The following code may cause memory leakage in the ie series.
Copy codeThe Code is as follows:
Var s = "lalala ";
Alert (s. length );

S itself is a string rather than an object, and it does not have the length attribute. Therefore, when length is accessed, the JS engine will automatically create a temporary String object to encapsulate s, and this object will be leaked. This bug is incredible. Fortunately, it is quite easy to solve. Remember to explicitly convert all value types before performing. Operations:
Copy codeThe Code is as follows:
Var s = "lalala ";
Alert (new String (s). length );

7. Some DOM operations
The unique problem of the IE series is simply to appendChild to the DOM element not on the DOM tree; In IE7, it seems that to improve memory leakage, IE7 adopts an extreme solution: reclaim all elements on the DOM tree when you leave the page.

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.