From what I understand, the JS garbage collector removes objects that are no longer referenced. Suppose I remove a reference to an object and that object has a property which is a reference to another object. Will both objects be removed?
e.g
var objectA = {
prop1: "property",
prop2: "property"
}
var objectB = {
refToA: objectA
}
// Remove reference to objectA
delete objectA;
// Remove reference to objectB
delete objectB
Are both objects now completely removed from memory?
Short answer: Yes. An object that isn’t referenced anywhere is completely removed from memory, regardless of what is referenced by that objects properties.
In your snippet, things are fairly straightforward, though mem-management can get tricky when you start using closures:
Basically, objects are nameless entities. The variables used to access them are references, the never, ever contain the actual object itself. That floats around in JS-space. When you use
delete someVar, all you do is unset the actual value of that variable, which is a memory address (sort of).If the JS GC can’t find any variables that reference a location in memory that contains an object, it will reclaim that memory.
It’s as simple as that.
When you apply this logic to the following code:
In the previous example, the last delete statement would haven sufficed to GC the closure object literal. However, now
objAhas two methods (properties that reference function objects). These methods still reference the closure object, and are still referenced byobjA, so theclosureObjcan’t be GC’ed yet. So, this is where things get tricky:We’ve deleted all properties that can link back to the
closureObj, so it stands to reason that it’ll be GC’ed, right? –Erm, not quite. Chrome’s V8 does deallocate the memory, but I’ve heard of similar code causing leaks in Opera, and it’s not out of the realm of possibility’s that perhaps IE will not excel at reclaiming the memory.Also, we’ve effectively created a getter method with
getClosureReference, so in real life, this is very likely to occur:In this case, the
closureObjcan’t be GC’ed, because it’s still being referenced byobjBsomewhere. Only when that variable goes out of scope willclosureObjbe deallocated. Not only is this a very solid argument against global variables (they never go out of scope, and thus never get GC’ed), it also goes to show that closures, neat though they are, require some more overhead from the developer: letting a variable go out of scope doesn’t necessarily mean the memory is freed: some closure could expose a reference to an object, or a function that references that object…I’ve posted a question on this matter a while ago but it might explain a few things.
And just for fun, if you want an example of nested closures (closers in closures, in closures, passing references to each other, and other objects) try finding out when what can be GC’ed in the following code