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
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
Share
Improve this question
edited Feb 22, 2018 at 10:51
Kunj
2,0182 gold badges23 silver badges34 bronze badges
asked Feb 22, 2018 at 10:43
Fopa Léon ConstantinFopa Léon Constantin
12.4k9 gold badges52 silver badges84 bronze badges
2
- keep in mind that variable is still in memory even when it is set as undefined and will take space. – Arpit Solanki Commented Feb 22, 2018 at 10:46
- 2 The best way for the GC to collect this is to make it go out of scope. – Keith Commented Feb 22, 2018 at 10:48
1 Answer
Reset to default 12In 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 panies (UPS, FedEX, etc). Each box has an address, and each pany 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.