如何在javascript中释放闭包的内存? [英] how to release closure's memory in javascript?
问题描述
闭包:
function test() {
var count = 0;
return function() {
count++;
};
}
众所周知, count
在调用 test()
后不会释放,现在如果闭包对我没有用,我该如何释放内存呢?
As we all know, the count
won't release after test()
be called, and now if the closure is useless to me, how could I release memory of it?
推荐答案
javascript中的所有对象都是垃圾收集的,无论它们是否参与关闭都不受天气影响.在上面的代码中,如果您这样做:
All objects in javascript is garbage collected, regardless of weather they're involved in a closure or not. In your code above, if you do:
var x = test();
然后当然不能释放用于 count
的内存,因为以后可能会被 x
使用.但是,如果您这样做:
then of course the memory for count
cannot be released because it may be used later by x
. However if you do:
var x = test();
x = "";
count
的内存迟早会被垃圾回收.
the memory for count
will be garbage collected sooner or later.
此外,如果您这样做:
function foo () {
var x = test();
x();
}
foo();
count
的内存也将被垃圾回收,因为当 foo()
结束时, x
超出范围.
the memory for count
would also be garbage collected because x
goes out of scope when foo()
ends.
确保您的JavaScript中没有内存泄漏的最佳方法是避免使用全局变量.
The best way to ensure you don't have memory leaks in javascript is to avoid global variables.
注意:IE的旧版本中的垃圾收集器使用简单的引用计数,这意味着不会对垃圾桶中的循环数据结构进行垃圾收集.这已在IE6或IE7中修复,在其他通常使用标记清除垃圾收集器的JavaScript引擎中从来没有问题
Note: The garbage collector in old versions of IE used a simple reference count which means that circular data structures are not garbage collected. This was fixed in either IE6 or IE7 and was never a problem in other javascript engines which normally use a mark-and-sweep garbage collector
这篇关于如何在javascript中释放闭包的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!