Skip to content
Advertisement

Does deleting a property before replacing it change garbage collecting priority?

If you are replacing a property on an object that is a reference to a giant object, does it ever make sense to delete that property before replacing it?

const a = {
  child: b //Reference to big object
}
delete a.child;
a.child = c; //Another big object

vs

const a = {
  child: b //Reference to big object
}
a.child = c; //Another big object

Advertisement

Answer

No, it does not make any difference at all for garbage collecting. Unlike it’s name the delete operator just removes a property of an object. It does not delete memory or free anything on its own or give anything “deletion priority”. If the property that is being removed contains a reference to an object, then removing the property will release one reference to that object.

So, all delete a.child does is remove the child property from the a object and thus release a reference count for whatever a.child was previously pointing at. If whatever a.child points to has no other references to it, then it will become eligible for garbage collection right after the delete a.child statement. Garbage collection in Javascript is generally not immediate though as it will run at some time later when there appear to be free cycles to run the GC algorithm.

But, as soon as you do a.child = c the same object it was previously pointing at would also become eligible for garbage collection (if there are no other references to whatever it was pointing at).

So, either way its eligible for garbage collection (or not if there are other references to it) at exactly the same time.

And, removing the property and then adding it again just creates more work for the JS engine than just assigning a new value to the existing property. In fact, removing the property and then adding it back again might even kick it out of certain JS engine optimizations because it’s not a known predictable set of properties that can be more optimized than dynamically changing sets of properties.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement