javascript - 什么是 JavaScript 垃圾回收?

标签 javascript garbage-collection

什么是 JavaScript 垃圾回收?为了编写更好的代码,对于 Web 程序员来说,了解 JavaScript 垃圾收集有什么重要意义?

最佳答案

Eric Lippert 写了一个 detailed blog post不久前关于这个主题(另外将其与 VBScript 进行比较)。更准确地说,他写了关于 JScript ,这是微软自己的 ECMAScript 实现,虽然与 JavaScript 非常相似。我想您可以假设 Internet Explorer 的 JavaScript 引擎的绝大多数行为都是相同的。当然,实现会因浏览器而异,但我怀疑您可以采用一些通用原则并将它们应用于其他浏览器。

引自该页面:

JScript uses a nongenerational mark-and-sweep garbage collector. It works like this:

  • Every variable which is "in scope" is called a "scavenger". A scavenger may refer to a number, an object, a string, whatever. We maintain a list of scavengers -- variables are moved on to the scav list when they come into scope and off the scav list when they go out of scope.

  • Every now and then the garbage collector runs. First it puts a "mark" on every object, variable, string, etc – all the memory tracked by the GC. (JScript uses the VARIANT data structure internally and there are plenty of extra unused bits in that structure, so we just set one of them.)

  • Second, it clears the mark on the scavengers and the transitive closure of scavenger references. So if a scavenger object references a nonscavenger object then we clear the bits on the nonscavenger, and on everything that it refers to. (I am using the word "closure" in a different sense than in my earlier post.)

  • At this point we know that all the memory still marked is allocated memory which cannot be reached by any path from any in-scope variable. All of those objects are instructed to tear themselves down, which destroys any circular references.

垃圾回收的主要目的是让程序员担心他们创建和使用的对象的内存管理,当然有时也无法避免 - 拥有它总是有益的至少大致了解垃圾收集的工作原理。

历史记录:答案的早期版本对 delete 运算符的引用不正确。在 JavaScript the delete operator removes a property from an object , 和 C/C++ 中的 delete 完全不同。

关于javascript - 什么是 JavaScript 垃圾回收?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/864516/

相关文章:

javascript - 缩小 Canvas 内图表的大小

c# - Asp.Net 核心 api 中未释放内存

javascript - 需要设置时间值00 :00:00 in DatePicker date value

javascript - 模块.js :491 throw err;

javascript - Redux——繁重的工作应该在哪里发生——reducer、action、容器还是表示组件?

memory-management - delete() 是立即释放内存还是需要 runtime.GC() 来释放它?

go - 生产中的 FreeOSMemory()

javascript - 扩展类时将对象作为元/标记传递。这是什么语法,它有什么作用?

java - 为什么看似不必要地触发 G1 Full GC?

c# - 垃圾收集和终结器 : Finer Points