Reference Counting

Reference counting is one way of handling memory management.

The idea is that we keep track of how many places in a program that an object is ‘referenced’ from. i.e. we have a pointer from. Everytime we add a new reference we increment the reference count. Everytime we remove a reference we decrement the reference count.

When the reference count goes to zero then we can delete the object.

Sounds grand but in practise reference reference counting runs into a few problems:

  • Overhead - reference counting can be slow

    • For instance our string class used to be reference counted. Andew Vajoczki replaced the implementation with a non reference counted implementation and sped up Iguana by a factor or 2 or more in the first week he worked at the company.

  • Circular references can be a problem

    • A → B → C → A

    • Therefore objects never get cleared up.

  • Not threadsafe

    • If we have different threads touching the same reference count we can get conflicts which will result in memory corruption. Keeping our string class reference counted wouldn’t have allowed us to implement Iguana 4 which was the first multi-threaded version of Iguana.

More reading in wikipedia: https://en.wikipedia.org/wiki/Reference_counting