gpt4 book ai didi

javascript - 在关闭选项卡/窗口之前删除变量是否有助于释放内存?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:00:58 26 4
gpt4 key购买 nike

我正在维护一个 JavaScript 代码,其中一个函数执行一些繁重的处理以生成数组,并将结果保存在函数本身内部的缓存变量中。它是这样实现的:

function heavyProcessingStuff(x) {
if(heavyProcessingStuff.cache == undefined)
heavyProcessingStuff.cache = [];

if(heavyProcessingStuff.cache[x] != undefined) {
return heavyProcessingStuff.cache[x]
} else {
return heavyProcessingStuff.cache[x] = x + 1
}
}

奇怪的是,当页面被卸载时,有一个函数会手动删除缓存变量的每个属性,就像这样:

for (n in heavyProcessingStuff.cache) {
delete heavyProcessingStuff.cache[n]
}

我很困惑为什么要这样实现。
这是否特定于某些奇怪的 Angular 落案例?有这样做的动机吗?页面关闭时,浏览器是否/不应该收集所有垃圾?

最佳答案

Javascript 使用垃圾收集,最好不要显式释放内存。在文章 "Writing Fast, Memory-Efficient JavaScript" 中的“取消引用误解”中可以很好地阅读这一点.

文章引述:

It’s not possible to force garbage collection in JavaScript. You wouldn’t want to do this, because the garbage collection process is controlled by the runtime, and it generally knows best when things should be cleaned up.

关于javascript - 在关闭选项卡/窗口之前删除变量是否有助于释放内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25434781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com