Search code examples
javascriptgarbage-collectionprimitive

Is it necessary to nullify primitive values for grabage collection?


If I have the following code:

function MyClass() {
    this.data = {
        // lots of data
    };
}

var myClassInstace = new MyClass();

var myobj = {
    num:123,
    str:"hello",
    theClass:myClassInstance
};

I know it's absolutely necessary to do:

myobj.theClass = null;

To free up myClassInstance and its data property for GC. However, what should I do with myobj.num and myobj.str? Do I have to give them a value of null too? Does the fact that they're primitive change anything regarding GC?


Solution

  • The JavaScript runtime that implements garbage collection will be able to collect items as soon as values are no longer reachable from code. This is true for object references as well as primitives. The details of the exact moment the item is collected varies by implementation, but it is not even necessary to set your object references to null (as you state) unless you need the object cleaned up sooner than the natural termination of the current function.

    This all ties into the fundamental concept of "scope" and the Scope Chain. When an item is no longer in any other objects scope chain it can be collected. Understanding this clearly will answer this question and also help to understand closures, which are scenarios where items stay in memory longer than you might have expected.