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!
Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as garbage collection (GC). The purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it.
Garbage collection is performed automatically. We cannot force or prevent it. Objects are retained in memory while they are reachable. Being referenced is not the same as being reachable (from a root): a pack of interlinked objects can become unreachable as a whole, as we've seen in the example above.
WeakMaps provide a way to extend objects from the outside without interfering with garbage collection. Whenever you want to extend an object but can't because it is sealed - or from an external source - a WeakMap can be applied.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With