weakMap 和 map 的垃圾回收对比

江枫思渺然 提交于 2020-08-05 04:27:45

https://segmentfault.com/a/1190000022940544

WeakMap 介绍

WeakMap 对象是一组键/值对的集合,其中的键是 弱引用 的。
WeakMap 的 key 只能是 Object 类型。
原始数据类型是不能作为 key 的(比如 Symbol)。
WeakMap只有四个方法可用:get()set()has()delete()
**
具体属性和方法介绍,可查看 《MDN WeakMap》。

3.2 WeakMap 应用

原文中介绍了“通过 WeakMap 缓存计算结果”和“在 WeakMap 中保留私有数据”两种应用场景。
另外还有一种比较常见的场景:以 DOM节点作为键名的场景


场景1:当我们想要为DOM添加数据时,可使用 WeakMap 

场景2:当我们想要为DOM元素添加事件监听时,可使用 WeakMap 

 

使用--expose-gc 开启手动gc

结果表明,weakMap在key对象被回收时,会自动将对应的映射也回收掉

并且weakmap对于对象的引用不计入引用计数器

 

代码

分别调用两次测试函数,保证结果与调用顺序无关

const objNum = 64 * 1024;

function usageSize() {
  const used = process.memoryUsage().heapUsed;
  return Math.round((used / 1024 / 1024) * 100) / 100 + "M";
}

function testMap() {
  const curType = " Map "
  global.gc();
  console.log(1, curType + '占用内存:' + usageSize());

  const map = new Map();
  let arr = Array(objNum).fill().map((_, index) => Object.create({index}))
  map.set(arr, 1)
  global.gc();
  console.log(2, curType + '占用内存:' + usageSize());
  arr = null;
  global.gc();
  console.log(3, curType + '占用内存:' + usageSize());
  console.log("=====")
}

function testWeakMap() {
  const curType = " WeakMap "
  global.gc();
  console.log(1, curType + '占用内存:' + usageSize());
  let arr = Array(objNum).fill().map((_, index) => ({index}))

  const map = new WeakMap();

  map.set(arr, 1)
  global.gc();
  console.log(2, curType + '占用内存:' + usageSize());

  arr = null;
  global.gc();
  console.log(3, curType + '占用内存:' + usageSize());
  console.log("=====")
}


testMap()
testWeakMap()
testWeakMap()
testMap()

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!