内存管理

内存的生命周期:Allocate -> Use -> Release。


理解 Heap & Stack 的概念。


理解 GC 的概念,常见的 GC 算法。(Reference CountingMark & Swipe

可以尝试和 java 中 JVM 的 GC 算法类比。


内存泄露常见的 cases 以及避免方法。

  • 全局变量污染。
  1. function foo(f) {
  2. this.foo = f;
  3. }
  4. // call without new, and this will refer to the window as
  5. // a global variable
  6. f('hi');
  • timers / callbacks 遗忘清除。即时清除 Observers / Timeout Callbacks
  • 闭包中,未使用的变量创建的闭包。
  • 多 DOM References 未清理导致内存仍然保留。
var elements = {
    button: document.getElementById('button'),
    image: document.getElementById('image')
};

function doStuff() {
    elements.image.src = 'http://example.com/image_name.png';
}

function removeImage() {
    // The image is a direct child of the body element.
    document.body.removeChild(document.getElementById('image'));
    // At this point, we still have a reference to #button in the
    //global elements object. In other words, the button element is
    //still in memory and cannot be collected by the GC.
}

Ref