弱参考演示

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 }