弱參考演示

JavaScript 使用引用計數技術來檢測未使用的物件。當物件的引用計數為零時,該物件將由垃圾收集器釋放。Weakmap 使用弱引用,它不會對物件的引用計數產生影響,因此它對解決記憶體洩漏問題非常有用。

這是一個 weakmap 的演示。我使用一個非常大的物件作為值來表明弱引用對引用計數沒有貢獻。

// manually trigger garbage collection to make sure that we are in good status.
> global.gc(); 
undefined

// check initial memory use,heapUsed is 4M or so
> process.memoryUsage(); 
{ rss: 21106688,
  heapTotal: 7376896,
  heapUsed: 4153936,
  external: 9059 }

> let wm = new WeakMap();
undefined

> const b = new Object();
undefined

> global.gc();
undefined

// heapUsed is still 4M or so
> process.memoryUsage(); 
{ rss: 20537344,
  heapTotal: 9474048,
  heapUsed: 3967272,
  external: 8993 }

// add key-value tuple into WeakMap,
// key is b,value is 5*1024*1024 array 
> wm.set(b, new Array(5*1024*1024));
WeakMap {}

// manually garbage collection
> global.gc();
undefined

// heapUsed is still 45M
> process.memoryUsage(); 
{ rss: 62652416,
  heapTotal: 51437568,
  heapUsed: 45911664,
  external: 8951 }

// b reference to null
> b = null;
null

// garbage collection
> global.gc();
undefined

// after remove b reference to object,heapUsed is 4M again 
// it means the big array in WeakMap is released
// it also means weekmap does not contribute to big array's reference count, only b does.
> process.memoryUsage(); 
{ rss: 20639744,
  heapTotal: 8425472,
  heapUsed: 3979792,
  external: 8956 }