【发布时间】:2020-02-22 16:24:48
【问题描述】:
根据MDN,Mark and Sweep 是一种比引用计数更好的垃圾收集算法,因为它避免了循环引用可能发生的内存泄漏。但是,我不明白为什么会这样?有人可以(用代码)解释 Mark and Sweep 如何避免此类内存泄漏吗?随意使用来自 MDN 的以下代码,它解释了引用计数的工作原理:
var x = {
a: {
b: 2
}
};
// 2 objects are created. One is referenced by the other as one of its properties.
// The other is referenced by virtue of being assigned to the 'x' variable.
// Obviously, none can be garbage-collected.
var y = x; // The 'y' variable is the second thing that has a reference to the object.
x = 1; // Now, the object that was originally in 'x' has a unique reference
// embodied by the 'y' variable.
var z = y.a; // Reference to 'a' property of the object.
// This object now has 2 references: one as a property,
// the other as the 'z' variable.
y = 'mozilla'; // The object that was originally in 'x' has now zero
// references to it. It can be garbage-collected.
// However its 'a' property is still referenced by
// the 'z' variable, so it cannot be freed.
z = null; // The 'a' property of the object originally in x
// has zero references to it. It can be garbage collected.
另外,全局变量永远不会被垃圾回收吗?
【问题讨论】:
标签: javascript garbage-collection