Reputation: 1953
In the code below, does aObj
remain in memory after garbage collection? And what is the easiest way I can test and see this?
var a = function(arg) {
this.argument = arg;
}
var aObj = new a({ prop1: 1, prop2: 2 });
var b = aObj.argument;
aObj = null;
Upvotes: 0
Views: 41
Reputation: 1075635
No, it does not. After the aObj = null
line, there are no remaining references to the object it used to contain. It has a reference to argument
, but argument
doesn't have a reference to it, and so after you've released the only reference to the object (in aObj
), the object is eligible for garbage collection.
Let's stop the world just before the aObj = null
line and see what's in memory (leaving out some details):
+−−−−−−−−−−−−−−−+ a−−−−−−−−>| (function) | +−−−−−−−−−−−−−−−+ | (...) | +−−−−−−−−−−+ | prototype |−−−−+−−>| (object) | +−−−−−−−−−−−−−−−+ | +−−−−−−−−−−+ | | (...) | | +−−−−−−−−−−+ | +−−−−−−−−−−−−−−−+ | +−−>| (object) | | | +−−−−−−−−−−−−−−−+ | | | [[Prototype]] |−−−−+ +−−−−−−−−−−+ | | argument |−−−−+−−>| (object) | | +−−−−−−−−−−−−−−−+ | +−−−−−−−−−−+ | | | prop1: 1 | aObj−−+ | | prop2: 2 | | +−−−−−−−−−−+ b−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
Now, we do the aObj = null
line, and get:
+−−−−−−−−−−−−−−−+ a−−−−−−−−>| (function) | +−−−−−−−−−−−−−−−+ | (...) | +−−−−−−−−−−+ | prototype |−−−−+−−>| (object) | +−−−−−−−−−−−−−−−+ | +−−−−−−−−−−+ | | (...) | | +−−−−−−−−−−+ | +−−−−−−−−−−−−−−−+ | | (object) | | +−−−−−−−−−−−−−−−+ | | [[Prototype]] |−−−−+ +−−−−−−−−−−+ | argument |−−−−+−−>| (object) | +−−−−−−−−−−−−−−−+ | +−−−−−−−−−−+ | | prop1: 1 | aObj: null | | prop2: 2 | | +−−−−−−−−−−+ b−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
As you can see, nothing has a reference to that object anymore.
And what is the easiest way I can test and see this?
Chrome has a pretty advanced memory profiler which can, amongst other things, show you the number of objects from a given constructor that are still in memory. More on their dev tools site here.
Upvotes: 2