JavaScript 的垃圾收集
我有两段代码 示例 1
(function(){
var x = 1;
this.getx = function() { return x; };
})();
示例 2
(function(){
var x = 1;
this.getx = function() { };
})();
两个代码示例都创建了一个闭包,示例一中的 x 被引用,而示例二中的 x 未被引用,我知道示例一中的 x 不会被垃圾收集,我的问题示例二中的 x 会被垃圾收集吗?
I have two piece of code
sample 1
(function(){
var x = 1;
this.getx = function() { return x; };
})();
sample 2
(function(){
var x = 1;
this.getx = function() { };
})();
both code samples create a closure, x in sample one is referenced, while x in sample two is not referenced, I know x in sample one will not be garbage collected, my question will x in sample two be garbage collected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Javascript 中的垃圾收集是一个模糊的东西。一般来说,您可以假设(尽管我们知道假设的作用),一旦没有对变量的引用(例如,一旦超出范围),它将被垃圾收集。但是,您的闭包不会按您的预期工作,因为它们没有分配给任何东西;因此,您将没有函数对象可以调用 getx() 。但是,如果您要分配它,则
x
永远不会超出范围,除非您在保存函数引用的任何变量上使用delete
关键字。简单的规则:每当您担心收集时,请使用
delete
运算符 - 这将删除引用,并且更有可能释放内存。编辑:除了@chuckj的评论之外,无论您使用
delete
还是将变量分配给undefined
,仍然表明您希望将引用计数设置为0(如果有的话)是否有任何释放记忆的希望。Garbage collection in Javascript is a nebulous thing. Generally speaking, you can assume (though we know what assuming does) that once there are no references to a variable (eg, once it goes out of scope), it will be garbage collected. However, your closures will not work as you intend because they are not assigned to anything; thus you will have no function object to call
getx()
on. If you were to assign it, though,x
would never be out of scope unless you used thedelete
keyword on any variables holding the function reference.Simple rule: use the
delete
operator whenever you're concerned about collection - this will remove the reference, and it's more likely that the memory will be freed.Edit: comments by @chuckj aside, whether you use
delete
or assign the variable toundefined
still lends to the point that you want to get the reference count to 0 if there's to be any hope of freeing the memory.对于现代浏览器,示例二中的 x 将在大多数浏览器中被垃圾收集,除了 ie6
To modern browsers, x in sample two will be garbage collected in most browsers, except for ie6
ECMAScript 标准故意没有提及垃圾收集器应如何工作,因此实现可能会有所不同。但是,一般来说,如果某个对象无法从活动对象中引用,则会收集该对象。
在示例 2 中,这意味着闭包可能会被收集,但也可能不会创建闭包,因为函数没有引用它。闭包是昂贵的,现代 JavaScript 引擎会尽量避免创建它们,除非被迫。
The ECMAScript standard is intentionally silent on how the garbage collector should work so implementations are likely to differ. However, in general, if an object is not referencible from a live object it will be collected.
In sample 2 it means that the closure will likely be collected but it is also likely a closure will not even be created since the function does not reference it. Closures are expensive and modern JavaScript engines try to avoid creating them unless they are forced to.