开发者

garbage collection for javascript

开发者 https://www.devze.com 2023-01-20 12:41 出处:网络
I have two piece of code sample 1开发者_Python百科 (function(){ var x = 1; this.getx = function() { return x; };

I have two piece of code sample 1

开发者_Python百科
(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?


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.


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 the delete 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 to undefined 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.


To modern browsers, x in sample two will be garbage collected in most browsers, except for ie6

0

精彩评论

暂无评论...
验证码 换一张
取 消