Reputation: 741
I'm just doing some experiments with scoping in javascript. My question: In the following code snippet, will 'second' and 'third' be garbage collected? This could be of particular use when dealing with linked lists.
var first = {}
var second = first;
var third = second;
first = null;
Upvotes: 2
Views: 81
Reputation: 707716
No. second
and third
still have references to your object so it cannot yet be garbage collected.
When you do this:
var first = {};
var second = first;
Your variable second
does not have a reference to first
. It has a reference to the same object that first
points to. So, now you have two equal variables that both have a reference to the same object.
When you set:
first = null;
All, you did was clear the reference to that object in the first
variable. The object itself was not affected at all. And, most importantly to your question, the variable second
was not affected at all so it still has a reference to that object and thus it cannot be garbage collected.
For an object in Javascript to be garbage collected, there must be no live references to that object anywhere in the code that are in reachable code. As long as second
is still a reachable variable, the object it points to cannot be garbage collected.
If you know a language like C++ with pointers, then you can think of an assignment like you did in
var first = {};
like putting a pointer to your object into first
. first
doesn't actually contain the object itself. The object exists on its own. first
just contains a point to that object.
Then, when you do:
var second = first;
You create another variable and you get the pointer from first
and put a copy of that same point into second
. Now you have two completely separate variables that both contain a pointer to your object. Remember, the object exists on it's own so when you then do:
first = null;
All you are doing is clearing the pointer in first
. The object is still there and second
still contains a pointer to it. Since there's still a live pointer to it, the object will not be garbage collected.
For your object to be garbage collected, you would either need all three variables that contain a reference to the object to be cleared as in:
var first = {}
var second = first;
var third = second;
first = null;
second = null;
third = null;
Or, you would need all three variables to go out of scope so the variables themselves got garbage collected.
Upvotes: 4