Garbage collection

Reachability

主要管理記憶體的核心是可取得性,JavaScript 引擎裡有垃圾搜集器,監控並移除未使用的物件。

  • 目前函式的參數或變數

  • 內嵌函式所用到的變數及參數

  • 全域變數

A simple example

// user has a reference to the object
let user = {
  name: "John"
};

// 物件被移除,得不到物件的值 John
user = null;

Two references

// user has a reference to the object
let user = {
  name: "John"
};

let admin = user;

// 只修改 user 的指向,admin 仍存在物件,因此物件依然存在
user = null;

Interlinked objects

function marry(man, woman) {
  woman.husband = man;
  man.wife = woman;

  return {
    father: man,
    mother: woman
  }
}

let family = marry({
  name: "John"
}, {
  name: "Ann"
});
delete family.father;
delete family.mother.husband;

Unreachable island

family = null;

Internal algorithms

基本的垃圾蒐集演算法為 mark-and-sweep

  • 垃圾搜集器找尋所有根並標註。

  • 標註所有根指向的記憶,繼續往下一層標註記憶體直到沒有新的物件。

  • 未被標註的記憶體進行刪除。

Last updated