gpt4 book ai didi

Javascript 垃圾收集相关

转载 作者:行者123 更新时间:2023-12-02 13:49:20 25 4
gpt4 key购买 nike

在下面的代码中,垃圾回收后,aObj 是否仍保留在内存中?我可以测试和查看这一点的最简单方法是什么?

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

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

最佳答案

不,事实并非如此。在 aObj = null 行之后,不再有对其过去包含的对象的引用。 It 引用了 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−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

如您所见,没有任何东西再引用该对象。

And what is the easiest way I can test and see this?

Chrome 有一个非常先进的内存分析器,除其他外,它可以向您显示给定构造函数中仍在内存中的对象数量。更多关于their dev tools site here .

关于Javascript 垃圾收集相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41126003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com