Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

ecmascript 6 - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...