简体   繁体   English

函数中的对象的垃圾收集

[英]Garbage Collecting array of objects in a function

Let's say I have the following function: 假设我具有以下功能:

function myfunc() {
    var data = [];

    for (var i=0; i<10; i++) {
        data[i] = {foo:"bar"};
    }

    // do something with data
}

At the end of the function I no longer need any of the data. 在函数结束时,我不再需要任何数据。 What would be needed for it to be freed? 要释放它,需要什么?

As far as I know, something will be GCed if it can't be reached from the global object. 据我所知,如果无法从全局对象访问某些内容,则会对其进行GC处理。 If data is unreachable, then all of the elements inside would be unreachable too since data is the only reference to them. 如果data不可访问,那么内部的所有元素也将不可访问,因为data是对其的唯一引用。 So what's the right way to make data and everything in it GCable? 那么使data及其中的所有内容变为GC的正确方法是什么?

Would data = null do the trick if I put it at the end of the function? 如果将data = null放在函数末尾, data = null会成功吗?

Do I even need to do something at all? 我什至需要做些什么吗? Since data is a local variable in myfunc() , shouldn't it get destroyed once the function completes, thus making the data in data GCable? 由于data是在一个局部变量myfunc()应该不是被摧毁的一次函数完成,从而使数据data GCable?

Yes, you do not need to do anything. 是的,您无需执行任何操作。

If there are no other references to the objects that just went out of scope, they will be garbage collected. 如果没有其他对超出范围的对象的引用,则将对其进行垃圾回收。

These other references may come from unexpected places (such as an accidental closure that survives the function call, or attaching things to the browser DOM), but in general the mechanism works very reliably. 这些其他引用可能来自意外的地方(例如在函数调用后意外关闭,或者将内容附加到浏览器DOM),但总的来说,该机制非常可靠。 It takes care of reference cycles as well. 它也照顾参考周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM