Several cases of JS memory leak discuss _javascript skills in detail

Source: Internet
Author: User
Tags closure garbage collection tagname
A memory leak is a piece of allocated memory that is neither available nor recyclable until the browser process finishes. In C + +, memory leaks are a frequent occurrence because of the manual memory management. And now popular in C # and Java and other languages using automatic garbage collection method to manage memory, normal use of the case almost no memory leaks. Memory is also managed by the automatic garbage collection method in the browser, but a memory leak can occur because of a bug in the browser garbage collection method.

1, when the elements of the page are removed or replaced, if the element binding event has not been removed, in IE will not make the appropriate processing, at this time to manually remove the event, otherwise there will be memory leaks.
Copy Code code 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 into the following
Copy Code code 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 the event delegation
Copy Code code 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 Code code as follows:

var A=document.getelementbyid ("#xx");
var B=document.getelementbyid ("#xxx");
A.r=b;
B.r=a;

Copy Code code as follows:

var A=document.getelementbyid ("#xx");
A.r=a;

For pure ECMAScript objects, as long as no other objects refer to 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 will not find that the circular relationship between them is isolated from the other objects in the system and frees them. Eventually they will be kept in memory until the browser is closed.
3,
Copy Code code 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 and forms a closure. This produces a circular reference, the:dom-> closure->dom-> closure ... 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, and even if the DOM object is removed in DOM tree, the DOM object and the closure are not freed because of the existence of the circular reference. You can use the following methods to avoid this memory leak
Copy Code code as follows:

var elem = document.getElementById (' test ');
Elem.addeventlistener (' click ', function () {
Alert (' You clicked ' + This.tagname); No longer directly referencing Elem variables
});

4,
Copy Code code as follows:

function Bindevent ()
{
var obj=document.createelement ("XXX");
Obj.onclick=function () {
Even if it ' s a empty function
}
}

Closures are very easy to form a circular reference. If a function object that constitutes a closure is assigned to, 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 glance at a Web site that contains similar circular reference code (which usually appears on every page of the site) consumes a lot of (or even all) system memory.
Solution, define the event handler function externally, and remove the closure
Copy Code code as follows:

function Bindevent ()
{
var obj=document.createelement ("XXX");
Obj.onclick=onclickhandler;
}
function OnClickHandler () {
Do something
}

Or, in an external function that defines an event handler, deletes a reference to the DOM (as described in the JavaScript authoritative guide), in closures, the properties that are not available in the scope can be removed to reduce memory consumption. )
Copy Code code as follows:

function Bindevent ()
{
var obj=document.createelement ("XXX");
Obj.onclick=function () {
Even if it ' s a empty function
}
Obj=null;
}

5,
Copy Code code 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 a property reference that has been deleted still exists, some implementations of JavaScript may cause memory leaks due to this imprecise code. So when you destroy the object, you go through the property in the property and delete it in turn.
6. Automatic Type boxing Conversion
Do not believe that the following code in the IE series will cause memory leaks
Copy Code code as follows:

var s= "Lalala";
alert (s.length);

s itself is a string instead of object, it has no length property, so when length is accessed, the JS engine automatically creates a temporary string object package s, which is bound to leak. This bug is difficult to solve, but it's quite easy to fix it, remember all the value types do it. Before the operation, explicitly convert:
Copy Code code as follows:

var s= "Lalala";
Alert (new String (s). length);

7. Some DOM operations
The problem with the IE series is simply that in a DOM element appendchild;ie7 that is not on the DOM tree, seemingly to improve memory leaks, IE7 uses an extreme solution: to reclaim all elements of the DOM tree when leaving the page, regardless of the other.

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.