Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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!

like image 258
Bruno Mazza Avatar asked Apr 15 '18 10:04

Bruno Mazza


People also ask

Is garbage collection automatically in JavaScript?

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.

How do I force garbage collection in JavaScript?

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.

When would you use a WeakMap?

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.


1 Answers

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

like image 106
Tomasz Kula Avatar answered Oct 14 '22 17:10

Tomasz Kula