Suppose I create two objects:
var a = new SomeObject();
var b = document.getElementById("someElement");
/* Do something with those two object */
After do something with those two objects I need to clear them in case of memory leak.
The question is which one should I choose btween "null" and "undefined" that the Garbage Collector will prefer.
// firstly, remove DOM node
b.parentElement.remove(b);
// then clear the variants using "null" or "undefined"
a = null;
b = null;
/* or:
a = undefined;
b = undefined;
*/
Any comments will be appreciated!
The garbage collector works by keeping track of which objects are reachable by your code. The idea is that if an object is not reachable, the block of memory it occupies can be freed without breaking your program.
One way in which an object can be reached is if it's assigned to a variable. Assigning a new value to a variable that presently points to an object (e.g. by assigning null
to a
) will reduce the reference count on that object by one. When this or any object's reference count is reduced to zero, it will qualify for garbage collection.
All that said, it's not really important what value you use to replace the value of a variable, as long as it's not some other object that would otherwise be garbage collected. For this reason, both undefined
and null
will work.
Note that you only need to scrub variables like this if a variable remains reachable by your code after the function that the variable was declared in returns. This could happen if an anonymous function closes on the variable, if the variable is "global" (tacked onto the global
object or declared without the var
keyword), or if the variable is actually a field on an object that's still reachable.
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