Search code examples
javascriptgarbage-collectiongarbage

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. If data is unreachable, then all of the elements inside would be unreachable too since data is the only reference to them. So what's the right way to make data and everything in it GCable?

Would data = null do the trick if I put it at the end of the function?

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?


Solution

  • 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. It takes care of reference cycles as well.