JS Ext

Wednesday, November 7, 2012

Reference Counting Garbage Collection

Reference Counting is a mechanism for garbage collection.  Every object gets a counter.  When you create the object, the counter starts at zero.  When the object is no longer in scope, the counter gets decremented.  When another object or scope gets a reference to the object, it increments the counter by one.  During the decrement phase, if the counter gets set to zero, then the object gets destroyed.  Because the object is getting destroyed, it decrements the counter for all the objects that it uses.  If any of those objects' counters reaches zero, then they are destroyed.  This chain reaction destroys all objects that are no longer used....or so you think.

Advantages:
  1. Objects are destroyed as soon as they fall out of scope.  This means the program does not consume more memory than the program needs
    • Heap sizes grow and shrink based on the programs need
  2. Garbage Collection runs in constant time, since you don't have to search for objects to destroy
    • No stop-the-world garbage collection cycles


Disadvantages
  1. Cyclic pointers are not supported.  Imaging the scenario where you have object A that points to object B.  Then, imaging object B points back to object A.  The counters for both objects will never reach zero since they will always have someone pointing to them (each other).  This is called a memory leak
    • History Note: This is why older versions of Internet Explorer had a tendency to consume all of your memory.  The DOM tree and the javascript object tree were managed with reference counting
  2. The counters require synchronization, so there is a performance penalty for all counter changes in a multi-threaded environment
  3. Allocating memory still requires searching for an empty spot large enough to hold your object, so allocating memory takes longer
  4. Because of reason #3, sequentially created objects tend to not be local to each other
    • Commonly referred as Swiss Cheese Memory!
    • Due to non-locality, there is an increase in cache misses



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.