将对象设置为 null 时的 JavaScript(ES6)WeakMap 垃圾回收

JavaScript(ES6) WeakMap garbage collection when set an object to null(将对象设置为 null 时的 JavaScript(ES6)WeakMap 垃圾回收)
本文介绍了将对象设置为 null 时的 JavaScript(ES6)WeakMap 垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我刚刚读到 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 垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SCRIPT5: Access is denied in IE9 on xmlhttprequest(SCRIPT5:在 IE9 中对 xmlhttprequest 的访问被拒绝)
XMLHttpRequest module not defined/found(XMLHttpRequest 模块未定义/未找到)
Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How can I open a JSON file in JavaScript without jQuery?(如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?)
quot;Origin null is not allowed by Access-Control-Allow-Originquot; in Chrome. Why?(“Access-Control-Allow-Origin 不允许 Origin null在铬.为什么?)
How to get response url in XMLHttpRequest?(如何在 XMLHttpRequest 中获取响应 url?)