A detailed discussion of several cases of JS memory leakage

Source: Internet
Author: User
Tags tagname

Memory leak refers to a piece of allocated memory can not be used, and can not be recycled, until the end of the browser process, due to the browser garbage collection method has a bug, will create a memory leak, the following with you to discuss in detail the memory leaks in several cases

A memory leak refers to a piece of allocated memory that cannot be used or recycled until the browser process ends. In C + +, memory leaks are a frequent occurrence because of the manual management of memory. And now popular C # and Java and other languages use automatic garbage collection method to manage memory, in the case of normal use, there will be little memory leaks. The browser also uses the automatic garbage collection method to manage memory, but due to a bug in the browser garbage collection method, a memory leak occurs.

1, when the page element is removed or replaced, if the element binding event is still not removed, in IE will not be properly handled, the first time to manually remove the event, otherwise there will be a memory leak.

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 using event delegates

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.target.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=a;

Copy CodeThe code is as follows:
var A=document.getelementbyid ("#xx");
A.r=a;


For purely ECMAScript objects, as long as there are no other objects referencing objects A, B, which means they are only references to each other, they are still recognized and processed by the garbage collection system. However, in Internet Explorer, if any object in a circular reference is a DOM node or an ActiveX object, the garbage collection system does not find that the cyclic relationship between them is isolated from other objects in the system and frees them. Eventually they will be kept in 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 DOM node's Click event handler, which refers to a DOM object Elem, which forms a closure. This will result in a circular reference, the:dom-> closure->dom-> closure Package ... The DOM object is not freed until the closure is released, and the closure is present as an event handler for the DOM object, so the closure is not released until the DOM object is released, even if the DOM object is deleted in the DOM tree, and the DOM object and the closure are not freed due to the existence of this circular reference. This memory leak can be avoided in the following ways

Copy CodeThe code is as follows:
var elem = document.getElementById (' test ');
Elem.addeventlistener (' click ', function () {
Alert (' You clicked ' + This.tagname); No longer directly referencing the Elem variable
});


4.

Copy CodeThe code is as follows:
function Bindevent ()
{
var obj=document.createelement ("XXX");
Obj.onclick=function () {
Even if it ' s a empty function
}
}


Closures are very easy to make circular references. If a function object that constitutes a closure is assigned, such as an event handler for a DOM node, and a reference to that node is assigned to an active (or mutable) object in the scope of the function object, a circular reference exists.
Dom_node.onevent-<function_object. [[scope]]-<scope_chain-<activation_object.noderef-<dom_node.

It is easy to form such a circular reference, and a slight glance at a Web site that contains a similar circular reference code (usually appearing on every page of the site) consumes a lot (or even all) of the system memory.
Solution, define the event handler externally, and release the closure

Copy CodeThe code is as follows:
function Bindevent ()
{
var obj=document.createelement ("XXX");
Obj.onclick=onclickhandler;
}
function OnClickHandler () {
Do something
}


Or, in the external function that defines the event handler, remove the reference to the DOM (in the case of the JavaScript authoritative guide, in closures, the unused properties in the scope can be removed 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, the value of b.x is still 1. Because the deleted attribute reference still exists, in some implementations of JavaScript, there may be a memory leak due to this non-rigorous code. So when destroying an object, iterate through the properties in the property, and then delete it.
6. Automatic Type boxing Conversion
Don't believe it, the following code will cause a memory leak in the IE series

Copy CodeThe code is as follows:
var s= "Lalala";
alert (s.length);


s itself is a string instead of an object, it has no length property, so when the length is accessed, the JS engine automatically creates a temporary string object that encapsulates s, and this object is bound to leak. The bug is pretty easy to solve, and remember that all value types do. Explicitly convert before operation:

Copy CodeThe code is as follows:
var s= "Lalala";
Alert (new String (s). length);


7. Some DOM operations
The unique problem with the IE series is simply that, in the appendchild;ie7 of DOM elements that are not on the DOM tree, it seems that in order to improve memory leaks, IE7 uses an extreme solution: to reclaim all the elements of the DOM tree while leaving the page.

A detailed discussion of several cases of JS memory leakage

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.