JavaScript 内存管理

栈(Stack)与堆(Heap)

Memory on the heap is allocated, deallocated, and resized regularly during program execution

编译器编译代码时计算内存用量决定栈内存

int n; // 4 bytes
int x[4]; // 4 × 4 bytes
double m; // 8 bytes

int n = readInput(); // reads input from the user, memory usage unpredictable

垃圾回收(Garbage Collection)

某块内存是否未被继续使用是无法决定的

引用计数(Reference-counting)

An object is considered “garbage collectible” if there are zero references pointing to it

cycle reference problem

function f() {
  var o1 = {};
  var o2 = {};
  o1.p = o2; // o1 references o2
  o2.p = o1; // o2 references o1. This creates a cycle.
}

f();

标记清除(Mark-and-sweep)

Anything that a root cannot reach will be marked as garbage, so cycles are not a problem anymore.

As of 2012, all modern browsers ship a mark-and-sweep garbage-collector.

generational/incremental/concurrent/parallel garbage collection.

GCs are unpredictable. You can’t really tell when a collection will be performed.

most GC implementations share the common pattern of doing collection passes during allocation. If no allocations are performed, most GCs stay idle.

内存泄露(Memory Leak)

  • global variable
  • Timers or callbacks that are forgotten
  • Closures
var theThing = null;
var replaceThing = function () {
  var originalThing = theThing;
  var unused = function () {
    if (originalThing) // a reference to 'originalThing'
      console.log("hi");
  };
  theThing = {
    longStr: new Array(1000000).join('*'),
    someMethod: function () {
      console.log("message");
    }
  };
};
setInterval(replaceThing, 1000);
  • Out of DOM references If you keep a reference to a table cell (a tag) in your code and decide to remove the table from the DOM yet keep the reference to that particular cell, you can expect a major memory leak to follow. this single reference to the table cell would keep the whole table in memory.

参考资料

Memory_management Stack-based_memory_allocation Garbage collection Tracing_garbage_collection Memory Management(MDN) How JavaScript works: memory management + how to handle 4 common memory leaks