Discussion on JS Memory leakage methods and prevention methods (2), discussion on js
- Concept
- WHAT:
- Memory leakage means that a piece of allocated memory can neither be used nor recycled until the browser process ends. 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.
- WHY:
- 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.
- Quick Review
- HOW:
- There are various Memory leakage methods in different browsers. Currently, the following methods are found:
- 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 function writing outside bindEvent. Simply paste the following code:
- 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 = "str_0"; // Here is a variable
Obj. onclick = function (){
Alert (var0); // I want to visit var 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:
- Some DOM operations
- 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:
-
| |
<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 );
ParentDiv. removeChild (childDiv );
HostElement. removeChild (parentDiv );
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;
}
} |
- Automatic Type Packing Conversion
- 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 );