JavaScript is a garbage collection language, which means that the memory is allocated to the object based on the object creation and will be reclaimed by the browser when no reference is made to the object. The garbage collection mechanism of JavaScript 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 to process memory for DOM objects. 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 be returned to the heap. Although this solution is still effective in general, there are some blind spots in circular references.
Memory leakage may occur in the following modes:
1. Loop reference causes memory leakage. JavaScript Object obj has reference to DOM object, which is expressed as DivElement. The DOM object has reference to this JavaScript Object, represented by expandoProperty. 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, neither of them can be destroyed.
Obj = document. getElementById ("DivElement ");
Document. getElementById ("DivElement"). expandoProperty = obj;
Obj. bigString = new Array (1000). join (new Array (2000). join ("XXXXX "));
2. Memory leakage caused by external function calls. Create a circular reference by calling external function myFunction. Similarly, JavaScript objects and DOM
Cyclic reference between objects also results in Memory leakage.
Function myFunction (element)
{
This. elementReference = element;
// This code forms a circular reference here
// By DOM-> JS-> DOM
Element. expandoProperty = this;
}
Function Leak (){
// This code will leak
New myFunction (document. getElementById ("myDiv "));
}
3. Memory leakage caused by Javascript closures. The closure functions 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.
Function closureDemoParentFunction (paramA)
{
Var a = paramA;
Return function closureDemoInnerFunction (paramB)
{
Alert (a + "" + paramB );
};
};
Var x = closureDemoParentFunction ("outer x ");
X ("inner x ");
Javascript Memory leakage tool:
1. Drip/sIEve
2. Javascript Leaks Detector
3. Leak Monitor
For more information, see:
Http://www.ibm.com/developerworks/cn/web/wa-memleak/
Http://djjchobits.javaeye.com/blog/375465
Source: http://adamlu.com /? P = 418