A second, less-popular type of garbage collection is reference counting. The idea is that every value keeps track of how many references are made to it. When a variable is declared and a reference value is assigned, the reference count is one. If another variable is then assigned to the same value, the reference count is incremented. Likewise, if a variable with a reference to that value is overwritten with another value, then the reference count is decremented. When the reference count of a value reaches zero, there is no way to reach that value and it is safe to reclaim the associated memory. The garbage collector frees the memory for values with a reference count of zero the next time it runs.
Reference counting was initially used by Netscape Navigator 3.0 and was immediately met with a serious issue: circular references. A circular reference occurs when object A has a pointer to object B and object B has a reference to object A, such as in the following example:
var objectA = new Object();
var objectB = new Object();
objectA.someOtherObject = objectB;
objectB.anotherObject = objectA;
In this example, objectA and objectB reference each other through their properties, meaning that each has a reference count of two. In a mark-and-sweep system, this wouldn’t be a problem because both objects go out of scope after the function has completed. In a reference-counting system, though, objectA and objectB will continue to exist after the function has exited, because their reference counts will never reach zero. If this function were called repeatedly, it would lead to a large amount of memory never being reclaimed. For this reason, Netscape abandoned a reference- counting garbage-collection routine in favor of a mark-and-sweep implementation in version 4.0.
I don't see how objetA and objectB wouldn't continue to exist if the circular reference wouldn't be there. In other words, taking the circular reference out of the equation, in what moment objectA and objectB would reach a reference count of zero?
Thanks in advance!