Easy to cause JavaScript memory leaks in several ways
- 2020-03-30 03:51:18
- OfStack
Published in Google WebPerf (London WebPerf group), & # 8203; The & # 8203; August 26, 2014.
Efficient JavaScript Web applications must be smooth and fast. Any application that interacts with a user needs to think about how to ensure memory is used efficiently, because if it consumes too much, the page crashes, forcing the user to reload. And you're crying in a corner.
Automatic garbage collection is no substitute for effective memory management, especially in large, long-running Web applications. In this lecture, we will demonstrate how to manage memory effectively with Chrome's DevTools.
And learn how to solve performance problems such as memory leaks, frequent garbage collection pauses, and overall memory bloat, the things that really drain your energy.
Addy Osmani shows many examples of memory leaks in Chrome V8 in his powerpoint presentation:
1) Delete the property of an Object will make the Object slow (15 times more memory)
var o = { x: 'y' };
delete o.x; //O will be a slow object
o.x; //
var o = { x: 'y' };
o = null; //It should look like this
2) closure
When variables outside a closure are introduced into a closure, the object cannot be garbage collected (GC) when the closure ends.
var a = function() {
var largeStr = new Array(1000000).join('x');
return function() {
return largeStr;
}
}();
3) the DOM
When the original COM is removed, the child reference cannot be retrieved if it is not removed.
var select = document.querySelector;
var treeRef = select('#tree');
//In the COM tree, leafRef is a child of treeFre
var leafRef = select('#leaf');
var body = select('body');
body.removeChild(treeRef);
//#tree cannot be returned as treeRef is still in
//Solution :
treeRef = null;
//The tree cannot be recycled yet because the leaf result leafRef is still
leafRef = null;
//Now #tree can be released. < br / >
4) Timers leak
Timers are also a common source of memory leaks:
for (var i = 0; i < 90000; i++) {
var buggyObject = {
callAgain: function() {
var ref = this;
var val = setTimeout(function() {
ref.callAgain();
}, 90000);
}
}
buggyObject.callAgain();
//The timer is still at
even though you want to recycle it
buggyObject = null;
}
5) debug memory
Chrome's built-in memory debugging tool makes it easy to see memory usage and leaks:
In the Timeline - > Memory click on record:
Please see more content (link: https://speakerdeck.com/addyosmani/javascript-memory-management-masterclass).