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());
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With