Home  >  Article  >  Web Front-end  >  How to avoid JavaScript memory leaks and memory management techniques

How to avoid JavaScript memory leaks and memory management techniques

伊谢尔伦
伊谢尔伦Original
2016-11-23 10:24:15878browse

An efficient JavaScript web application must be smooth and fast. Any application that interacts with users needs to consider how to ensure that memory is used efficiently, because if too much is consumed, the page will crash, forcing the user to reload. And you can only hide in the corner and cry.

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 effectively manage memory through Chrome's DevTools.

 And learn how to troubleshoot performance issues like memory leaks, frequent garbage collection pauses, and overall memory bloat, the stuff that's really killing you.

 Addy Osmani showed many examples of memory leaks in Chrome V8 in his PPT:

 1) Delete properties of an Object will slow down the object (consuming 15 times more memory)

var o = { x: 'y' };
delete o.x; //此时o会成一个慢对象
o.x; //
 
var o = { x: 'y' };
o = null;  //应该这样

 2 ) Closure

When a variable outside the closure is introduced in the 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) DOM leak

When the original COM is removed, the child node references cannot be recycled unless they are removed.

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 leak

Timers are also a common place where memory leaks occur:

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) Debugging memory

Chrome’s own memory debugging tool can easily check memory usage and Memory leak:

  Click record in Timeline -> Memory:

How to avoid JavaScript memory leaks and memory management techniques

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:7 JavaScript TipsNext article:7 JavaScript Tips