Dmitry Minkovsky
Dmitry Minkovsky

Reputation: 38173

Does holding a reference to an object property prevent the object from being garbage collected?

Let's say I've got an object:

var o1 = {
    someKey: 'value'
};

and another object that references that first object:

var o2 = {
    o1Ref: o1
};

and also a third object that references a property on the first object:

var o3 = {
    o1propRef: o1.someKey
};

Then, let's say o2 is garbage collected. Does the reference to o1.someKey on o3 prevent o1 from being collected?

Then, also, suppose o1 is bigger, say:

var o1 = {
    someKey: 'value',
    someBigValue: Buffer(2000000)
};

Can the parts of o1 that aren't being referenced be collected, or are objects collected as a whole? It seems like, with the second version of o1, o3 is just holding on to o1.someKey and o1.someBigValue can be freed up.

Also, I do realize this might vary among implementations. If that's the case, whats' the best way to think about this generally?

Upvotes: 4

Views: 201

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074989

Does the reference to o1.someKey on o3 prevent o1 from being collected?

No, because there isn't one (a reference). You have a copy of the value of o1.someKey as of when you created the object, not a reference to the o1.someKey property. (JavaScript doesn't have references to anything but objects; so no property references, just object references.)

You can see that you're just getting the value as of the initialization by playing with it:

var o1 = {
    someKey: 'value'
};

var o3 = {
    o1propRef: o1.someKey // (It's not a property reference, it's a copy of the value, but I left the name alone)
};

console.log(o3.o1propRef);  // "value"
o1.someKey = "updated value";
console.log(o3.o1propRef);  // "value"
console.log(o1.someKey);    // "updated vale"

For o3 to prevent o1 from being garbage-collected, o3 would have to have a reference to o1 (or to something that in turn has a reference to it). Just getting a value from o1.someKey doesn't set up any kind of reference relationship at all.

Upvotes: 3

Related Questions