简体   繁体   English

将对象设置为 null 时的 JavaScript(ES6)WeakMap 垃圾回收

[英]JavaScript(ES6) WeakMap garbage collection when set an object to null

I've just read that WeakMaps take advantage of garbage collection by working exclusively with objects as keys, and that assigning an object to null is equivalent to delete it:我刚刚读到 WeakMaps 通过专门使用对象作为键来利用垃圾收集,并且将对象分配给 null 等效于删除它:

let planet1 = {name: 'Coruscant', city: 'Galactic City'};
let planet2 = {name: 'Tatooine', city: 'Mos Eisley'};
let planet3 = {name: 'Kashyyyk', city: 'Rwookrrorro'};

const lore = new WeakMap();
lore.set(planet1, true);
lore.set(planet2, true);
lore.set(planet3, true);
console.log(lore); // output: WeakMap {{…} => true, {…} => true, {…} => true}

Then I set the object equal to null:然后我将对象设置为null:

planet1 = null;
console.log(lore); // output: WeakMap {{…} => true, {…} => true, {…} => true}

Why is the output the same?为什么输出一样? Wasn't it supposed to be deleted so that the gc could reuse the memory previously occupied later in the app?难道不应该删除它,以便 gc 可以重用之前在应用程序中占用的内存吗? I would appreciate any clarification.我将不胜感激。 Thanks!谢谢!

Garbage collection does not run immediately.垃圾收集不会立即运行。 If you want your example to work you need to force your browser to run garbage collection.如果您希望您的示例工作,您需要强制您的浏览器运行垃圾收集。

Run chrome with the following flag: google-chrome --js-flags="--expose-gc" .使用以下标志运行 chrome: google-chrome --js-flags="--expose-gc"

You can now force the garbage collection by calling the global gc() method.您现在可以通过调用全局gc()方法来强制进行垃圾收集。

在此处输入图像描述

I was trying to figure out the same thing, in 2022, but it looks like the browsers don't bother to garbage collect if the WeakMap is small.我试图在 2022 年弄清楚同样的事情,但如果 WeakMap 很小,看起来浏览器不会费心进行垃圾收集。

But if you do something like this:但如果你这样做:

let weakmap = new WeakMap()

for (let i = 0; i < 2000; i++) {
    let john = {meow: i}

    weakmap.set(john, i)
    console.log(weakmap)
    john = null

    let div = document.createElement("div")
    div.innerText = i
    document.body.append(div)
    weakmap.set(div, i)
    div.remove()
}

let john2 = {} // Test to see if it garbage collects this (it shouldn't)

weakmap.set(john2, "random")

console.log(weakmap)

Then the browser will garbage collect after a certain size:然后浏览器会在一定大小后进行垃圾收集: 在此处输入图像描述

As you can see it went from the size to 4001 too 101. It looks like the browser doesn't bother garbage collecting the rest.如您所见,它的大小从 4001 也变为 101。看起来浏览器不会打扰垃圾收集其余部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM