Javascript垃圾收集相关

时间:2016-12-13 16:30:45

标签: javascript

在下面的代码中,垃圾收集后aObj是否仍留在内存中?我能测试和看到这个最简单的方法是什么?

var a = function(arg) {
    this.argument = arg;    
}

var aObj = new a({ prop1: 1, prop2: 2 });    
var b = aObj.argument;    
aObj = null;

1 个答案:

答案 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