I am looking for an explicit way to be sure that JavaScript garbage collector will do its job pretty soon.
So does setting a variable to undefined
is a guarantee?
var foo = "something";
// do stuff with foo
foo = undefined;
// awake the Garbage Collector interest to him
In theory no, it won't be gargage collected. There's still a reference in memory to this variable. The fact that it contains an undefined value is irrelevant.
Imagine RAM like a giant storage of boxes. Those boxes are shared between different companies (UPS, FedEX, etc). Each box has an address, and each company tells some central application "hey, the box at this address is being used by me". So even if you empty or undefine the box, there's still a 1:1 connection between let's say UPS and that box. In the same way your JS interpreter tells your operating system ("hey, the memory location at xxx is being used by me, don't assign it to anybody else").
The fact that it contains an undefined value doesn't free this memory location. Your operating system does not know nor care what's in that memory location, he knows it's assigned to your JS interpreter, and your JS interpreter linked it to your variable foo.
You shouldn't be troubling yourself with garbage collection in JS anyway. As long as you create your variables in the right places and don't flood the global object (but even then I doubt you're gonna have much problems) every variable is going to be garbage collected automatically as soon as it can't be used.
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