7

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!

Bruno Mazza
  • 445
  • 7
  • 20
  • 1
    "*assigning an object to null is equivalent to delete it*" - no, removing the reference from your variable does make the object *eligible* for garbage collection (when that happens). It does not immediately delete anything. – Bergi Apr 15 '18 at 12:55
  • https://stackoverflow.com/questions/38203446/javascript-weakmap-keep-referencing-gced-objects – Bergi Apr 15 '18 at 12:58
  • Also, these things will all get garbage collected as soon as GC runs since WeakMap doesn't retain a reference to the object. You need to store references to the planets somewhere else or the WeakMap will immediately throw them away. – podperson Feb 25 '21 at 22:43

1 Answers1

10

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.

enter image description here

Tomasz Kula
  • 13,215
  • 1
  • 51
  • 71