Wednesday, March 21, 2012

Javascript Garbage Collection

There's a student yesterday asking about garbage collection in Javascript.  And here it is how it works from  a high level perspective.

Memory is allocated to objects when they created and reclaimed by the browser when there are no more reference to it.  A garbage collection is a mechanism that saved developer time or effort from explicitly performing memory management task and its main duty is to  determine when it is safe to reclaim the memory.   Of course, if an item is still being referenced or being used, it won't collect those memory.   It only collects the memory from objects that are no longer reachable or referenced.

But how does that works?  Well, most garbage collection is using different variants of "Mark-and-Sweep" method/algorithm.  In Javascript, it travsed periodically all the variables and objects and mark items that are still being used or referenced. And it follows with the "sweep" step, it sweep any "unmark" items and reclaim the memory back by deallocating those.

Ok, so how does those information help us?  

In Javascript, global scope variables are not garbage collectable and presenting opportunity for a memory leak, and it explains why we need to limit the usage of global variables in our program.  ( There are many reasons why you should limit the use of global variables, this is just one of the reasons ).

Whenever you create an object using a "new" statement, use a delete statement to explicitly destroy it when it is no longer needed.  This step ensures the memory of that object will be available to the garbage collection.

There is a blog post more on this topic:

No comments:

Post a Comment