問題描述
我剛剛讀到 WeakMaps 通過專門使用對象作為鍵來利用垃圾回收,并且將對象分配給 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}
然后我將對象設置為null:
Then I set the object equal to null:
planet1 = null;
console.log(lore); // output: WeakMap?{{…} => true, {…} => true, {…} => true}
為什么輸出相同?難道不應該刪除它,以便 gc 可以重用以前在應用程序中占用的內存嗎?我將不勝感激.謝謝!
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!
推薦答案
垃圾回收沒有立即運行.如果您希望您的示例正常工作,您需要強制您的瀏覽器運行垃圾收集.
Garbage collection does not run immediately. If you want your example to work you need to force your browser to run garbage collection.
使用以下標志運行 chrome:google-chrome --js-flags="--expose-gc"
.
Run chrome with the following flag: google-chrome --js-flags="--expose-gc"
.
您現在可以通過調用全局 gc()
方法來強制進行垃圾回收.
You can now force the garbage collection by calling the global gc()
method.
這篇關于將對象設置為 null 時的 JavaScript(ES6)WeakMap 垃圾回收的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!