在尝试理解JavaScript的WeakMaps / WeakSets时,我已经阅读了MDN文档。
写道:“ WeakSet很弱:对集合中对象的引用是弱的。如果没有其他对WeakSet中存储的对象的引用,它们可以被垃圾收集。 ”
完整文章:MDN
“它们可以被垃圾收集”是什么意思?
当我创建一个对象时。然后将它存储为WeakSet。然后将引用变量设置为null。
对象是否会自动从集中删除?
答案 0 :(得分:4)
我不确定上面是否显示了WeakSet正在做什么..
所以我在这里创建了一个片段来展示它。因为从浏览器中您通常无法访问GC,所以我已将其设置为控制台记录WeakSet,并等待您再次按下按钮和控制台日志。与此同时,您可以清除浏览器控制台并强制执行GC,清除控制台就像在Chrome控制台中一样完成日志记录,WeakSet也将最终保留对对象的引用。
如果您在Chrome浏览器中执行此操作,则应该看到WeakSet {{..}, {{..}}
,向我们显示WeakSet对2个对象的引用。清除控制台,强制GC,然后单击按钮后。另一个WeakSet将被控制台记录,它应显示WeakSet {{..}}
。基本上显示1个对象,证明GC已经完成了它的工作并仅保留对objectA
的引用。
注意:在chrome中强制执行GC,请转到性能选项卡,然后执行 一个看起来像垃圾箱️的图标,点击这个。
PS。如果您将代码段中的new WeakSet
更改为new Set
,并执行相同的操作,您会注意到该设置中仍有2个项目。这是Set和WeakSet之间的区别。
const ws = new WeakSet();
let objectA = {};
let objectB = {};
ws.add(objectA);
ws.add(objectB);
console.log(ws);
objectB = null;
document.querySelector("button").onclick = function () {
console.log(ws);
}
<p>Look inside Chrome console, you should see a WeakSet, and it should have two values in there. eg. <b>WeakSet {{..}},{..}}</b></p>
<p>Now clear the console, otherwise the console will keep a referece to the weakset entries, and either wait for a while, maybe 30 seconds, or go into chrome's Performace tab and click the collect garbage icon. After doing this, click the button below.</p>
<p>
<button>Click me after console clear and GC</button>
<p>After clicking the above button look in your console again, you should see a Weakset again, but with just one item. eg. <b>WeakSet {{..}}</b></p>
答案 1 :(得分:3)
这意味着垃圾收集器只会在WeakSet
或WeakMap
引用时从内存中删除该对象。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
var obj = {};
var array = new Array();
while(true) // don't do this
{
array.add(obj);
obj = null;
}
vs
var obj = {};
var ws = new WeakSet();
while(true) // don't do this
{
ws.add(obj);
obj = null;
}
在第二个示例中,由obj
分配的内存被清除,而在第二个示例中则没有。{/ p>