JS Memory leakage

Source: Internet
Author: User


Javascript
It is a garbage collection language, that is, the memory is allocated to the object based on the creation of the object, and will be reclaimed by the browser when there is no reference to the object. Javascript
The garbage collection mechanism is no problem, but the browser is somewhat different in the way of allocating DOM objects and Restoring memory.

Both Internet Explorer and Mozilla Firefox use reference count
Object Processing Memory. In the reference counting system, each referenced object retains a count to learn how many objects are referencing it. If the count is zero, the object will be destroyed and the occupied memory will return
Heap. Although this solution is still effective in general, there are some blind spots in circular references.

 

What are the problems with circular references?


When two objects reference each other, a circular reference is formed. The reference count value of each object is assigned
1. In a pure garbage collection system, loop reference is not a problem: if one of the two objects involved is referenced by any other object, both objects will be collected by garbage collection. In the reference counting system
Objects cannot be destroyed because the reference count cannot be zero. In a hybrid system that uses both garbage collection and reference count, leakage occurs because the system cannot correctly identify cyclic references. In this situation
The DOM object and JavaScript Object cannot be destroyed. Listing 1 shows the JavaScript Object and Dom
A circular reference between objects.

 

Listing 1. Loop reference causes memory leakage

 
<HTML> <br/> <body> <br/> <MCE: Script Type = "text/JavaScript"> <! -- <Br/> document. Write ("circular references between JavaScript and Dom! "); <Br/> var OBJ; <br/> window. onload = function () {<br/> OBJ = document. getelementbyid ("divelement"); <br/> document. getelementbyid ("divelement "). expandoproperty = OBJ; <br/> obj. bigstring = new array (1000 ). join (new array (2000 ). join ("XXXXX"); <br/>}; </P> <p> // --> </MCE: SCRIPT> <br/> <Div id = "divelement"> Div element </div> <br/> </body> <br/> </ptml>
 

As shown in the above list, the JavaScript Objectobj

Reference to a DOM object, representedDivElement

. The DOM object has reference to this JavaScript ObjectexpandoProperty

. It can be seen that a circular reference is generated between a JavaScript Object and a DOM object. Because Dom
Objects are managed by reference count, so neither of them can be destroyed.

 

Another memory leakage Mode


In Listing 2, by calling an external FunctionmyFunction

Create a circular reference. Similarly, circular references between JavaScript objects and DOM objects may cause memory leakage.

 

List 2. Memory leakage caused by external function calls

<HTML> <br/> <pead> <br/> <MCE: Script Type = "text/JavaScript"> <! -- <Br/> document. Write ("Object s between JavaScript and Dom! "); <Br/> function myfunction (element) {<br/> This. elementreference = element; <br/> // This code forms a circular reference here <br/> // by Dom --> JS --> Dom <br/> element. expandoproperty = This; <br/>}< br/> function leak () {<br/> // this code will leak <br/> New myfunction (document. getelementbyid ("mydiv"); <br/>}</P> <p> // --> </MCE: SCRIPT> <br/> </pead> <br/> <body onload = "leak () "> <br/> <Div id =" mydiv "> </div> <br/> </body> <br/> </ptml>


As shown in the two sample codes, circular references are easy to create. Loop references are particularly prominent in one of the most convenient programming structures of javascript: closures.

 

Closure in Javascript

Javascript allows nested functions. A nested internal function can inherit the parameters and variables of an external function and is private to the external function. Listing 3
Shows an example of an internal function.

Listing 3. An internal function

Function parentfunction (parama) <br/>{< br/> var A = parama; <br/> function childfunction () <br/>{< br/> return a + 2; <br/>}< br/> return childfunction (); <br/>}


Javascript developers use internal functions to integrate small practical functions into other functions. As shown in listing 3, this internal functionchildFunction

Access external functionsparentFunction

. When an internal function obtains and uses the variables of its external function, it is calledClosure
.

Understanding closures


Consider the code snippets shown in Listing 4.

Listing 4. A simple closure

<HTML> <br/> <body> <br/> <MCE: Script Type = "text/JavaScript"> <! -- <Br/> document. Write ("Closure demo !! "); <Br/> window. onload = <br/> function closuredemoparentfunction (parama) <br/>{< br/> var A = parama; <br/> return function closuredemoinnerfunction (paramb) <br/>{< br/> alert (a + "" + paramb); <br/> }; <br/> var x = closuredemoparentfunction ("outer X"); <br/> X ("inner X "); </P> <p> // --> </MCE: SCRIPT> <br/> </body> <br/> </ptml>


In the above list,closureDemoInnerFunction

Is in the parent FunctionclosureDemoParentFunction

Internal functions defined in. When usingExternal x
PairclosureDemoParentFunction

External function variablesA
The value is assignedExternal x
. The function returns a pointer to an internal function.closureDemoInnerFunction

Pointer, which is included in the VariableX
.

External FunctionsclosureDemoParentFunction

Local variableA
Even when the external function returns, it still exists. This is different from a programming language like C/C ++. in C/C ++, once the function returns, the local variable will no longer exist. In
In JavaScriptclosureDemoParentFunction

With PropertiesA
Will be created. This property includes valuesParama
, Also known"External X"
. Similarly, whenclosureDemoParentFunction

It returns an internal function.closureDemoInnerFunction

, This function is included in the VariableX
.

Because the internal function holds a reference to the variable of the external function, this includes an attribute.A
Will not be collected by garbage collection. When a pair has a parameter valueInner x
OfX
When calling, that isx("inner x")

, A warning message is displayed, indicating"Outer x innerx
".

Listing 4

Briefly explains Javascript
Closure. Closures are very powerful because they allow internal functions to retain access to the variables of this external function when the external function returns. Unfortunately, closures are very easy to hide.
Circular references between JavaScript objects and DOM objects.

 

Closures and circular references

In listing 5, the JavaScript Object (obj

) Include references to the DOM object (by ID"element"

Referenced ). While DOM elements have javascriptobj

. In this way, the circular reference between the created JavaScript Object and the DOM object will cause memory leakage.

Listing 5. Memory leakage mode caused by event processing

<HTML> <br/> <body> <br/> <MCE: Script Type = "text/JavaScript"> <! -- <Br/> document. write ("program to initialize strate memory leak via closure"); <br/> window. onload = function outerfunction () {<br/> var OBJ = document. getelementbyid ("element"); <br/> obj. onclick = function innerfunction () {<br/> alert ("Hi! I will leak "); <br/>}; <br/> obj. bigstring = new array (1000 ). join (new array (2000 ). join ("XXXXX"); <br/> // This is used to make the leak significant <br/> }; </P> <p> // --> </MCE: SCRIPT> <br/> <button id = "element"> click me </button> <br/> </body> <br/> </ptml>


Avoid Memory leakage

Fortunately, JavaScript
Memory leakage can be avoided. After you have determined the patterns that can cause cyclic reference, as we have done in the previous sections, you can start to deal with these patterns. Here, we will
Memory leakage mode caused by event processing

This example shows three methods to deal with known memory leaks.

Solution 5

The solution for Memory leakage in is to make this JavaScript Objectobj

This explicitly breaks this circular reference, as shown in Listing 6.

Listing 6. Breaking circular references

<HTML> <br/> <body> <br/> <MCE: Script Type = "text/JavaScript"> <! -- <Br/> document. write ("avoiding memory leak via closure by breaking the circular <br/> reference"); <br/> window. onload = function outerfunction () {<br/> var OBJ = document. getelementbyid ("element"); <br/> obj. onclick = function innerfunction () <br/>{< br/> alert ("Hi! I have avoided the leak "); <br/> // some logic here <br/>}; <br/> obj. bigstring = new array (1000 ). join (new array (2000 ). join ("XXXXX"); <br/> OBJ = NULL; // This breaks the circular reference <br/> }; </P> <p> // --> </MCE: SCRIPT> <br/> <button id = "element"> "Click here" </button> <br/> </body> <br/> </ptml>


Listing 7 is to avoid circular references between JavaScript objects and DOM objects by adding another closure.

Listing 7. Add another Closure

<HTML> <br/> <body> <br/> <MCE: Script Type = "text/JavaScript"> <! -- <Br/> document. write ("avoiding a memory leak by adding another closure"); <br/> window. onload = function outerfunction () {<br/> var anotherobj = function innerfunction () <br/>{< br/> // some logic here <br/> alert ("Hi! I have avoided the leak "); <br/>}; <br/> (function anotherinnerfunction () {<br/> var OBJ = document. getelementbyid ("element"); <br/> obj. onclick = anotherobj}) (); <br/>}; </P> <p> // --> </MCE: SCRIPT> <br/> <button id = "element"> "Click here" </button> <br/> </body> <br/> </ptml>


In listing 8, another function is added to avoid the closure and prevent leakage.

Listing 8. Avoid closure itself

<HTML> <br/> <pead> <br/> <MCE: Script Type = "text/JavaScript"> <! -- <Br/> document. Write ("avoid leaks by avoiding closures! "); <Br/> window. onload = function () <br/>{< br/> var OBJ = document. getelementbyid ("element"); <br/> obj. onclick = doesnotleak; <br/>}< br/> function doesnotleak () <br/>{< br/> // your logic here <br/> alert ("Hi! I have avoided the leak "); <br/>}</P> <p> // --> </MCE: SCRIPT> <br/> </pead> <br/> <body> <br/> <button id = "element"> "Click here" </button> <br/> </body> <br/> </ptml>


Conclusion

This article explains how loop reference causes memory leakage in JavaScript --
Especially when closure is integrated. You also learned some common memory leak modes that involve cyclic references and several simple methods to deal with these leak modes.

  • Drip-0.5.rar
    (135.3 KB)
  • SIEve-0.0.8.exe.zip
    (195.4 KB)
  • Test_ie.html.zip
    (1.4 kb)
  • Extpatch.rar
    (562.3 KB)
  • Understanding_and_solving_internet_explorer_leak_patterns.rar
    (43 KB)
  • Management
    Clear ie' Memory leakage formula. rar
    (23.1 kb)
  • Jsleaksdetector.msi.zip
    (216.6 KB)
  • Winleak_1.1.3.zip
    (22.6 KB)

From: http://wv1124.javaeye.com/blog/524896

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.