Posted in 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 that memory is used effectively, because if it consumes too much, the page crashes and forces the user to reload. And you can only hide in the corner to cry.
Automatic garbage collection is not a substitute for effective memory management, especially in large, long-running web applications. In this lecture, we will demonstrate how to effectively manage memory through Chrome's devtools.
and learn how to address performance issues such as memory leaks, frequent garbage collection pauses, and overall memory bloat, something that really consumes your energy.
Addy Osmani shows many examples of memory leaks in Chrome V8 in his ppt:
1) Delete the property of an object slows this object (15 times times more memory is consumed)
123456 |
var o = { x: ‘y‘ }; delete o.x; //此时o会成一个慢对象 o.x; // var o = { x: ‘y‘ }; o = null ; //应该这样 |
2) Closures
When a variable outside the closure is introduced into the closure, the object cannot be garbage collected (GC) when the closure ends.
123456 |
var a = function () {    var Largestr = new array (1000000). Join ( ' x '    return function () {      return LARGESTR;    } } (); |
3) Dom leaks
When the original COM is removed, the child node references are not removed and cannot be reclaimed.
1234567891011121314151617 |
var select = document.querySelector;
var treeRef = select(
‘#tree‘
);
//在COM树中leafRef是treeFre的一个子结点
var leafRef = select(
‘#leaf‘
);
var body = select(
‘body‘
);
body.removeChild(treeRef);
//#tree不能被回收入,因为treeRef还在
//解决方法:
treeRef =
null
;
//tree还不能被回收,因为叶子结果leafRef还在
leafRef =
null
;
//现在#tree可以被释放了。
|
4) Timers (fixed) time device leakage
Timers are also a common place to generate memory leaks:
1234567891011121314 |
for (
var i = 0; i < 90000; i++) {
var buggyObject = {
callAgain:
function
() {
var ref =
this
;
var val = setTimeout(
function
() {
ref.callAgain();
}, 90000);
}
}
buggyObject.callAgain();
//虽然你想回收但是timer还在
buggyObject =
null
;
}
|
5) Debug Memory
Chrome's own memory debugging tool makes it easy to see memory usage and memory leaks:
Click on the record in Timeline-I:
For more information, please see the original PPT.
Original address: Click here
How to avoid JavaScript memory leaks and memory management tips