JavaScript WeakMap继续引用gc' ed对象

时间:2016-07-05 12:26:50

标签: javascript garbage-collection ecmascript-6 weakmap

我正在体验JavaScript弱图,在谷歌浏览器开发者控制台中尝试此代码后,运行--js-flags =" - expose-gc",我不明白为什么如果a是gc' ed,那么weakmap会继续引用ab。

PyYAML=3.11

1 个答案:

答案 0 :(得分:2)

在您的示例代码中,您没有发布a变量。它是一个顶级var,永远不会超出范围,永远不会被明确地取消引用,所以它保留在WeakMap中。一旦在代码中没有对象的引用,WeakMap / WeakSet就会释放它们。在您的示例中,如果您在console.log(a)个来电之后gc(),您仍然希望a还活着,对吗?

所以这是一个工作示例,显示WeakSet的运行情况以及一旦所有对它的引用都消失后它将如何删除:https://embed.plnkr.co/cDqi5lFDEbvmjl5S19Wr/

const wset = new WeakSet();

// top level static var, should show up in `console.log(wset)` after a run
let arr = [1];
wset.add(arr);

function test() {
  let obj = {a:1}; //stack var, should get GCed
  wset.add(obj);
}

test();

//if we wanted to get rid of `arr` in `wset`, we could explicitly de-reference it
//arr = null;

// when run with devtools console open, `wset` always holds onto `obj`
// when devtools are closed and then opened after, `wset` has the `arr` entry,
// but not the `obj` entry, as expected
console.log(wset);

请注意,打开Chrome开发工具可以防止某些对象被垃圾收集,这使得操作更难以实现:)