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

标签 javascript performance optimization memoization

我正在维护一个 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/

相关文章:

javascript - 如何使用 jQuery 以编程方式选择变量内的选项

javascript - 使用 javascript 切换显示 div。开始隐藏,点击显示

php+mysql : copying a row from one table to another

algorithm - 初始解接近最优的多元函数优化

javascript - Promise.then(a, b) 和 Promise.then(a).catch(b) 一样吗?

javascript - 如何对使用的特定 jQuery(和 Javascript)方法/函数进行特征检测/测试

python - 查找落在给定范围之间的索引

performance - sqlite即使索引也很难查询

performance - 有关strlen不同实现的性能的问题

ios - 如何优化代码并快速加载 UIPickerView 数据?