Next | Up

What is reference counting

Reference counting is not full garbage collection, since it cannot detect detached cycles of unreference objects. However it is of use in limited domains where cycles are not generated. An example is in OS's where the mapping between resources and resource-users is maintained via reference counting.

Each object that is the destination of a pointer has a count field, and this is maintained to record exactly how many pointers exist that point to the object. The operations of allocating/pointer-creation, duplicating a pointer, and destroying a pointer all have to maintain this count.

When the act of destroying a pointer reduces count to zero, then the object is garbage and is reclaimed (if it itself contains pointers, then these are recursively subject to the destroy-pointer operation).

Problems with reference counting

Despite being a very straightforward technique, most languages and compilers supporting pointers do not support the hooks required on pointer creation, duplication and deletion, and so it has to be explicitly coded, and the cases of pointer duplication have to be accurately identified by the programmer.

It is quite inefficient - no other technique involves any overhead in copying pointers, for instance, nor of recursively visiting an objects contents when the last pointer to it vanishes.

It doesn't detect or reclaim cycles.

It requires a count field in each object.

Advantages of reference counting

It recycles dead objects immediately upon their becoming unreachable - promptness - which is very useful for finalization purposes.

It is easy to implement correctly, and objects to do not have to be moved or copied.

Last updated by Tue 16 January 1996