本文介绍了JavaScript垃圾收集器处理全局变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我看到几条不同的评论后,我对此感到困惑。我正在阅读一本JavaScript书籍,它提到将全局变量设置为null是很好的做法(假设没有其他引用),并且GC在下一次扫描时为此变量回收内存。我看到其他评论说,全局变量永远不会被GC处置。



当在OOP结构中编写JavaScript时,如果我有这样的东西会发生什么(游戏在全球范围内):

  var game = {}; 
game.level = 0;
game.hero =新英雄();
//做东西
game.hero = null;

因为英雄居住在游戏中存储的对象中,而游戏存在于全局环境中,所以如果我设置为英雄实例为null,这是由GC处理吗?

解决方案

GC不会处理全局变量全局变量仍然存在的意义。然而,将它设置为 null 将允许收集它引用的内存。



Eg



之前:

 全局 - > {nothingness} 

后:

 全局 - > var a  - >对象{foo:bar} 

设置 a null

 全局 - > var a  - > null 

这里,对象使用的内存将有资格收集。变量 a 仍然存在,它只是引用 null



从不收集全局变量的说法有点误导。可以更准确地说,任何可追溯到全球背景的记忆目前都不适合收藏。



在回答你的问题时,是的 - 英雄对象将有资格收集,因为它与全局上下文的间接连接已被切断。


I'm confused about this since I've seen several different comments. I'm reading a javascript book where it mentions that setting global variables to null is good practice (assuming there are no other references) and the GC reclaims memory for this variable on it's next sweep. I've seen other comments that say global variables are never disposed by the GC.

Also when programming javascript in a OOP structure, what happens if I have something like this (where game is in the global context):

var game = {};
game.level = 0;
game.hero = new hero();
//do stuff
game.hero = null;

Since hero lives inside an object which is stored in game, which is in a global context, If I set for instance hero to null, would this be disposed by the GC?

解决方案

Global variables are never disposed of by the GC in the sense that a global variable will still exist. Setting it to null will allow the memory that it references to be collected, however.

E.g.

Before:

global -> {nothingness}

After:

global -> var a -> object { foo: "bar" }

Set a to null:

global -> var a -> null

Here, the memory used by the object will be eligible for collection. The variable a still exists though, and it simply references null.

The statement that global variables are never collected is slightly misleading. It might be more accurate to say that any memory that is traceable back to the global context is not currently eligible for collection.

In answer to your question, yes - the hero object will be eligible for collection, because its indirect connection to the global context has been severed.

这篇关于JavaScript垃圾收集器处理全局变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:11