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.

 
<Div id = "mydiv"> <input type = "button" value = "Click me" id = "mybtn"> </div> <SCRIPT type = "text/JavaScript">VaRBTN = Document. getelementbyid ("mybtn"); BTN. onclick=Function() {Document. getelementbyid ("Mydiv"). innerhtml = "processing ...";}</SCRIPT>

Should be changed to the following

<Div id = "mydiv"> <input type = "button" value = "Click me" id = "mybtn"> </div> <SCRIPT type = "text/JavaScript">VaRBTN = Document. getelementbyid ("mybtn"); BTN. onclick=Function() {BTN. onclick=Null; Document. getelementbyid ("Mydiv"). innerhtml = "processing ...";}</SCRIPT>

Or useEvent Delegate

<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,

VaR A = Document. getelementbyid ("# xx ");
VaR B = Document. getelementbyid ("# XXX ");
A. r = B;
B. R =;

 

 
VaRA = 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,

 
VaRELEM = Document. getelementbyid ('test'); ELEM. addeventlistener ('Click ',Function() {Alert ('You clicked' +ELEM. tagname );});

 

This sectionCodeRegister an anonymous function as a click event handler for a DOM node. The function references a DOM object ELEM to form 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:

VaRELEM = Document. getelementbyid ('test'); ELEM. addeventlistener ('Click ',Function() {Alert ('You clicked' +This. Tagname );//No longer directly referencing ELEM Variables});

 

4,

FunctionBindevent (){VaROBJ = 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.

FunctionBindevent (){VaROBJ = Document. createelement ("XXX"); Obj. onclick=Onclickhandler ;}FunctionOnclickhandler (){//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 .)

FunctionBindevent (){VaROBJ = Document. createelement ("XXX"); Obj. onclick=Function(){//Even if it's a empty Function} OBJ=Null;}

 

5,

 
A = {P: {X: 1}; B=A. P;DeleteA. 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.

 
VaRS ="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:

 
VaRS = "lalala"; Alert (NewString (s). Length );

7,Some Dom operations

 The unique issue 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.

This article first: http://www.cnblogs.com/sprying/archive/2013/05/31/3109517.html

The knowledge above comes from JavaScript advancedProgramDesign and JavaScript authoritative guide and http://www.cn-cuckoo.com/2007/08/01/understand-javascript-closures-72.html#clSto

Http://www.uml.org.cn/site/201205294.asp

Memory-related http://bbs.phpchina.com/thread-221214-1-1.html for JavaScript Advanced Programming

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.