Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are anonymous objects garbage collected in Javascript?

If I create an object without assigning it to anything, when will Javascript garbage collect this object? Here is an example:

alert(new Date().getTime());

If no such garbage collection is done, will this cause a memory leak?

for (var i = 0; i < 99999999; i++) {
    console.info(new Date().getTime());
}
like image 470
JoJo Avatar asked May 07 '12 19:05

JoJo


2 Answers

If nobody in scope is referencing the anonymous objects, they'll get garbage collected the next time the GC runs.

So, after Console.info finishes running, they're up for garbage collecting. If you set any in-scope variables to refer to them, then they won't.

like image 69
MushinNoShin Avatar answered Nov 15 '22 21:11

MushinNoShin


The beauty of garbage collection is that you dont know when the memory will be reclaimed, nor should you care (unless it's happening far too frequently).

In this situation, the runtime should eventually reclaim those Date instances, but nothing you do is really going to change how fast it does that. Also, this does NOT cause a memory leak.

like image 40
Tejs Avatar answered Nov 15 '22 21:11

Tejs