Javascript Memory leakage

Source: Internet
Author: User
Tags chrome developer chrome developer tools

1. What is memory leakage?

Memory leakage means that the memory allocated to the application cannot be re-allocated, even if the memory is no longer used. Normally, the garbage collector recycles DOM elements and event processors when they are not referenced or accessed. However, memory leakage in earlier versions of IE (IE7 and earlier) is very likely to occur, because the Memory Manager cannot correctly understand the Javascript lifecycle and does not recycle the memory before the lifecycle is broken (you can assign a value to null.

2. Why do you need to pay attention to it?

Memory leakage is a common unexpected programming error in large Web applications. Memory leakage reduces the performance of Web applications until the wasted memory exceeds what the system can allocate. As a Web developer, developing an application that meets functional requirements is only the first step. performance requirements are equally important to the success of Web applications, moreover, it may cause application errors or browser crashes.

3. What are the main causes of Memory leakage in Javascript?

1) circular reference

A simple example: a DOM object is referenced by a Javascript object, and the same or other Javascript objects are referenced at the same time. This DOM object may cause memory leakage. Reference of this DOM object will not be reclaimed by the garbage collector when the script is stopped. To break the circular reference, the reference of the DOM element object or DOM object must be assigned null.

2) Javascript Closure

Because of the limitations of the Javascript Scope, many implementations depend on Javascript without packaging. Please refer to my previous article JavaScript Scope and Closure. If you want to learn more about the Closure problems.

The closure can cause memory leakage because the internal method maintains a reference to the external method variables, so although the method returns the internal method, it can continue to access the private variables defined in the external method. The best practice for Javascript programmers is to disconnect all event processors before page reloading.

3) DOM Insertion Sequence

When two DOM objects in different ranges are added together, a temporary object is created. When the DOM object changes the scope to document, the temporary object will be useless. That is to say, DOM objects should be added from the top DOM elements on the current page until the remaining DOM elements are added. In this way, they always have the same scope and do not generate temporary objects.

4) how to detect?

Memory leakage is generally difficult for developers to detect because it is caused by unexpected errors in a large amount of code, but it does not affect the functions of the program before the system memory is insufficient. This is why someone collects application performance metrics during a long test period to test performance.

The simplest way to detect memory leakage is to use the task manager to check memory usage. Open the application in the new tab of the Chrome browser and check whether the memory usage is increasing. Other debugging tools, such as Chrome Developer Tools, provide memory monitors. This is a tutorial on the features of heap Analysis on Google's website.

 


 

What is memory leakage?
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.
Memory leakage Quick View
There are various Memory leakage methods in different browsers. Currently, the following methods are found:
1. circular reference
Leaked Browser: IE6.0 FF2.0
Loop reference containing DOM objects will cause memory leakage in most mainstream browsers. Here there are two simple concepts:
Reference: a. Property = B, and a references B
Circular reference: in short, if a references B, B references a, and a and B, a and B constitute a circular reference.
Circular references of a and B:
Var a = new Object;
Var B = new Object;
A. r = B;
B. r =;
Cycle a references itself:
Var a = new Object;
A. r =;
Circular references are common and harmless in most cases. However, when DOM objects or ActiveX objects are involved in circular references, circular references may cause memory leakage. Replacing any new Object in this example with document. getElementById or document. createElement will cause memory leakage.
Although this seems easy to understand, it is complicated because of closure participation, and loop references caused by closure are hard to be noticed. Below is a very common dynamic binding event:
Function bindEvent ()
{
Var obj = document. createElement ("XXX ");
Obj. onclick = function (){
// Even if it's a empty function
}
}
When this bindEvent is executed, 100% of the memory will be leaked. Someone may ask, where is the circular reference? Circular references involving closure and scope chain are complex and will not be discussed in detail here. There is a simple way to judge: A function will indirectly reference all objects it can access. The obj. onclick function can access the external variable obj, so it references obj and obj references it. Therefore, this event binding will cause memory leakage. In IBM's article, we introduced two methods to solve similar problems: obj = null, and onclick functions written outside bindEvent. I will not talk about them again. Simply paste the following code:
Function bindEvent ()
{
Var obj = document. createElement ("XXX ");
Obj. onclick = onclickHandler;
}
Function onclickHandler (){
// Do something
}
Function bindEvent ()
{
Var obj = document. createElement ("XXX ");
Obj. onclick = function (){
// Even if it's a empty function
}
Obj = null;
}
Both of these methods interrupt the loop reference and solve the problem, but it seems to have caused some damage to the Code expression ability. Suppose there is such a problem:
Function bindEvent ()
{
Var obj = document. createElement ("XXX ");
Var var0 = "OOXX"; // Here is a variable
Obj. onclick = function (){
Alert (var0); // I want to visit var2 here!
}
Return obj; // bindEvent must return obj!
}
Okay, the two methods won't work. If I write the function out, var0 won't be able to access it. If I make obj null, how can I return it? This is not a fantasy. It is actually a simple abstraction of DOM controls customized with JS: Creating DOM elements, setting private attributes, and binding events. Therefore, we must update two methods. First, method 1. To allow the function to access certain variables, we can use a Builder function to customize the onclick external closure:
Function bindEvent ()
{
Var obj = document. createElement ("XXX ");
Var var0 = "OOXX"; // Here is a variable
Obj. onclick = onclickBuilder (var0); // you can transfer anyone you want to access !!
Return obj; // bindEvent must return obj!
}
Function onclickBuilder (var0) // it corresponds to the above. The best parameter name also corresponds
{
Return function (){
Alert (var0 );
}
}
The second method is to let the chpn student from 51js execute obj = null after return !!
Function bindEvent ()
{
Try {
Var obj = document. createElement ("XXX ");
Var var0 = "OOXX"; // Here is a variable
Obj. onclick = function (){
Alert (var0); // I want to visit var2 here!
}
Return obj; // bindEvent must return obj!
} Finally {
Obj = null;
}
}
2. Some DOM operations on www.2cto.com
This is a special issue of the IE series. Simply put, it is To appendChild, a DOM element not on the DOM tree, which may cause memory leakage (only possible, the specific reason is unknown, and it seems very complicated, in the following example, removing onClick can also prevent leakage ). Therefore, the appendChild sequence may affect memory leakage. For example, from Microsoft:
</Html>
 
<Head>
 
<Script language = "JScript">
 
Function LeakMemory ()
 
{
 
Var hostElement = document. getElementById ("hostElement ");
 
// Do it a lot, look at Task Manager for memory response
 
For (I = 0; I <5000; I ++)
 
{
 
Var parentDiv =
 
Document. createElement ("<div onClick = 'foo () '> ");
 
Var childDiv =
 
Document. createElement ("<div onClick = 'foo () '> ");
 
// This will leak a temporary object
 
ParentDiv. appendChild (childDiv );
 
HostElement. appendChild (parentDiv );
 
HostElement. removeChild (parentDiv );
 
ParentDiv. removeChild (childDiv );
 
ParentDiv = null;
 
ChildDiv = null;
 
}
 
HostElement = null;
 
}
 
Function CleanMemory ()
 
{
 
Var hostElement = document. getElementById ("hostElement ");
 
// Do it a lot, look at Task Manager for memory response
 
For (I = 0; I <5000; I ++)
 
{
 
Var parentDiv =
 
Document. createElement ("<div onClick = 'foo () '> ");
 
Var childDiv =
 
Document. createElement ("<div onClick = 'foo () '> ");
 
// Changing the order is important, this won't leak
 
HostElement. appendChild (parentDiv );
 
ParentDiv. appendChild (childDiv );
 
HostElement. removeChild (parentDiv );
 
ParentDiv. removeChild (childDiv );
 
ParentDiv = null;
 
ChildDiv = null;
 
}
 
HostElement = null;
 
}
 
</Script>
 
</Head>
 
<Body>
 
<Button onclick = "LeakMemory ()"> Memory Leaking Insert </button>
 
<Button onclick = "CleanMemory ()"> Clean Insert </button>
 
<Div id = "hostElement"> </div>
 
</Body>
 
</Html>
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, regardless of other elements. But this not only does not play any role, but makes the problem more complex. For this type of problem, in addition to consciously bypassing these disgusting things, more useless suggestions such as innerHTML are used. I think we can slightly improve it by overwriting document. createElement:
First, we define an invisible element as a waste bin. All newly created elements are thrown into the bin. This ensures that all DOM elements are on the DOM tree and IE7 can be correctly recycled, on the other hand, we can avoid the so-called "Memory leakage caused by incorrect appendChild sequence ".
Function MemoryFix (){
 
Var garbageBox = document. createElement ("div ");
 
GarbageBox. style. display = "none ";
 
Document. body. appendChild (garbageBox );
 
Var createElement = document. createElement;
 
Document. createElement = function (){
 
Var obj = Function. prototype. apply. apply (createElement, [document, arguments]);
 
GarbageBox. appendChild (obj );
 
Return obj;
 
}
 
}
3. Automatic Type Packing Conversion
Don't believe it. The following code may cause memory leakage in the ie series.
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:
Var s = "lalala ";
Alert (new String (s). length );

 


From tsl0922 @ oschina

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.