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

Bru*_*zza 7 javascript null garbage-collection weakmap ecmascript-6

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}
Run Code Online (Sandbox Code Playgroud)

Then I set the object equal to null:

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

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!

Tom*_*ula 7

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.

在此处输入图片说明

  • 2020 更新:内存和性能选项卡上现在有一个收集垃圾图标,可以强制进行垃圾收集。 (4认同)