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

不问归期 提交于 2019-11-27 06:12:40

问题


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:

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:

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? I would appreciate any clarification. Thanks!


回答1:


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".

You can now force the garbage collection by calling the global gc() method.



来源:https://stackoverflow.com/questions/49841096/javascriptes6-weakmap-garbage-collection-when-set-an-object-to-null

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