/ˈrɛfərəns ˈkaʊntɪŋ/
noun … “Track object usage to reclaim memory.”
Reference Counting is a memory management technique in which each object maintains a counter representing the number of references or pointers to it. When the reference count drops to zero, the object is no longer accessible and can be safely deallocated from heap memory. This method is used to prevent memory leaks and manage lifetimes of objects in languages like Python, Swift, and Objective-C.
Key characteristics of Reference Counting include:
- Increment on reference creation: each time a new pointer or reference points to the object, the counter increases.
- Decrement on reference removal: when a reference goes out of scope or is reassigned, the counter decreases.
- Immediate reclamation: memory is freed as soon as the reference count reaches zero.
- Cyclic reference challenge: objects referencing each other can prevent the counter from reaching zero, requiring additional mechanisms like weak references or cycle detectors.
- Integration with dynamic memory: works on heap allocations to ensure efficient memory usage.
Workflow example: Reference counting in pseudocode:
obj = new Object() -- reference count = 1
ref1 = obj -- reference count = 2
ref2 = obj -- reference count = 3
ref1 = null -- reference count = 2
ref2 = null -- reference count = 1
obj = null -- reference count = 0; object is deallocated
Here, Reference Counting tracks how many active references exist to an object and frees it automatically once no references remain.
Conceptually, Reference Counting is like a shared library card: each person using the book adds their name to the card. Once everyone returns the book and removes their name, the book is eligible to be removed from the shelf.
See Heap, Memory Management, Garbage Collection, Pointer, Weak Reference.