Reference counting (Definition)

The manner in which we keep track of object usage.

Using the new operator creates a new object with a reference count of zero. Assigning that object creation to a variable increments the reference count as does storing it in an array or saving it as an object property. Deleting a variable containing a reference to an object decrements the reference count for that object.

When you assign the result of a new operation to a variable, first the object gets instantiated and stored and a reference to it is stored in the variable. If you assign the variable to another, you copy the reference. Now two variables are referring to the same object. Modifying the object that one points at modifies the other.

Using the delete operator on one variable removes a reference to the object. The other variable continues to refer to it and the object must remain persistent while it does. When no variables are referring to the object and there are no other references such as items in arrays or properties in other objects, the reference count is zero.

When the reference count is zero, the object can be garbage collected. Also, because there are no references to it, you have no handle by which you can reach it, so if it isn't garbage collected, it will waste the space it occupies. When that happens, you have a memory leak.

You would not normally have any access to the reference count for a variable and indeed, some implementations may use a different technique to manage garbage collection. However, it is a useful concept and allows the idea of objects, references and garbage collection be more easily understood.

See also:delete, Function arguments, Garbage collection, Memory leak, Object(), Option(), Variable