This article mainly introduces several aspects that may easily cause JavaScript Memory leakage. This article describes several examples that may cause memory leakage in ChromeV8, for more information, see Google WebPerf (London WebPerf group), August 26, 2014.
Efficient JavaScript Web applications must be smooth and fast. Any application that interacts with the user needs to consider how to ensure the effective use of memory, because if the consumption is too large, the page will crash and force the user to reload. You can only hide in the corner and cry.
Automatic garbage collection cannot replace effective memory management, especially in large, long-running Web applications. In this lecture, we will demonstrate how to effectively manage the memory through Chrome's DevTools.
Learn how to solve performance problems, such as memory leakage, frequent garbage collection pauses, and overall memory expansion, which truly consumes your energy.
Addy Osmani shows many examples of Memory leakage in Chrome V8 in his PPT:
1) Deleting an Object attribute slows down the Object (15 times more memory consumption)
The Code is as follows:
Var o = {x: 'y '};
Delete o. x; // at this time, o will become a slow object.
O. x ;//
Var o = {x: 'y '};
O = null; // this should be the case
2) Closure
When a variable outside the closure is introduced to the closure, the object cannot be garbage collection (GC) when the closure ends ).
The Code is as follows:
Var a = function (){
Var largeStr = new Array (1000000). join ('x ');
Return function (){
Return largeStr;
}
}();
3) DOM Leakage
When the original COM is removed, the sub-node reference cannot be recycled if it is not removed.
The Code is as follows:
Var select = document. querySelector;
Var treeRef = select ('# tree ');
// In the COM tree, leafRef is a subnode of treeFre.
Var leafRef = select ('# leaf ');
Var body = select ('body ');
Body. removeChild (treeRef );
// # Tree cannot be returned because treeRef is still
// Solution:
TreeRef = null;
// Tree cannot be recycled because leafRef
LeafRef = null;
// Now # the tree can be released.
4) leakage of Timers Timer
The timer is also a common cause of Memory leakage:
The Code is as follows:
For (var I = 0; I <90000; I ++ ){
Var buggyObject = {
CallAgain: function (){
Var ref = this;
Var val = setTimeout (function (){
Ref. callAgain ();
},90000 );
}
}
BuggyObject. callAgain ();
// Timer is still
BuggyObject = null;
}
5) debugging memory
Chrome's built-in memory debugging tool allows you to conveniently view memory usage and Memory leakage:
In Timeline-> Memory, click record:
For more information, see the original PPT.