在下面的代码中,垃圾收集后aObj
是否仍留在内存中?我能测试和看到这个最简单的方法是什么?
var a = function(arg) {
this.argument = arg;
}
var aObj = new a({ prop1: 1, prop2: 2 });
var b = aObj.argument;
aObj = null;
答案 0 :(得分:2)
不,它没有。在aObj = null
行之后,没有对它曾经包含的对象的剩余引用。 引用了argument
,但argument
没有对 it 的引用,因此在您发布了唯一的引用之后对象(在aObj
中),该对象有资格进行垃圾收集。
让我们在aObj = null
行之前停止世界,看看内存中有什么(省略一些细节):
+−−−−−−−−−−−−−−−+ a−−−−−−−−>| (function) | +−−−−−−−−−−−−−−−+ | (...) | +−−−−−−−−−−+ | prototype |−−−−+−−>| (object) | +−−−−−−−−−−−−−−−+ | +−−−−−−−−−−+ | | (...) | | +−−−−−−−−−−+ | +−−−−−−−−−−−−−−−+ | +−−>| (object) | | | +−−−−−−−−−−−−−−−+ | | | [[Prototype]] |−−−−+ +−−−−−−−−−−+ | | argument |−−−−+−−>| (object) | | +−−−−−−−−−−−−−−−+ | +−−−−−−−−−−+ | | | prop1: 1 | aObj−−+ | | prop2: 2 | | +−−−−−−−−−−+ b−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
现在,我们执行aObj = null
行,然后获取:
+−−−−−−−−−−−−−−−+ a−−−−−−−−>| (function) | +−−−−−−−−−−−−−−−+ | (...) | +−−−−−−−−−−+ | prototype |−−−−+−−>| (object) | +−−−−−−−−−−−−−−−+ | +−−−−−−−−−−+ | | (...) | | +−−−−−−−−−−+ | +−−−−−−−−−−−−−−−+ | | (object) | | +−−−−−−−−−−−−−−−+ | | [[Prototype]] |−−−−+ +−−−−−−−−−−+ | argument |−−−−+−−>| (object) | +−−−−−−−−−−−−−−−+ | +−−−−−−−−−−+ | | prop1: 1 | aObj: null | | prop2: 2 | | +−−−−−−−−−−+ b−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
正如您所看到的,任何事物都不再有对该物体的引用。
我能测试和看到这个最简单的方法是什么?
Chrome有一个非常先进的内存分析器,除其他外,它可以显示给定构造函数中仍在内存中的对象数。更多关于their dev tools site here。