Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
dodov Avatar asked Nov 06 '16 17:11

dodov


2 Answers

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.

like image 144
Scott Marcus Avatar answered Nov 15 '22 13:11

Scott Marcus


There are a lot of "it depends here", ranging from what your code is doing to what browser you're running in. However, if your object is JIT compiled to not use a map for its attributes, then the number should be an 8 byte double stored inline inside the object. Nulling it will do nothing.

The string and the myclass instance will be a pointer to memory allocated outside the object (since a string can be arbitarily many bytes, it can't be stored inside the object. A compiler could conceivably store one instance of the string in memory and never free it, however). Nulling them can allow the garbage collector to free them before the main object goes out of scope.

However, the real question is why you're worried about this. Unless you have profiled your code and identified garbage collection or memory leaks as a problem, you should not be trying to optimize GC behavior. In particular, unless your myobj object is itself going to be live for a long time, you should not worry about nulling fields. The GC will collect it when it goes out of scope.

like image 29
Justin Blank Avatar answered Nov 15 '22 14:11

Justin Blank