Reference counting

Swift uses a garbage collection technique called ARC, which stands for Automatic Reference Counting. Each time a heap allocated object is assigned to a variable, the object’s reference counter is incremented by one. When the variable is set to nil/null or falls out of scope, its object’s reference counter is decremented by one. When the reference counter reaches zero, the object is immediately deallocated.

Reference counting has both its advantages and disadvantages. Its main advantage is that the running time of the program becomes predictable, making it suitable for real-time systems. On the other hand, incrementing and decrementing an object’s reference counter each time the object is assigned to a variable or falls out of scope has a slight constant performance penalty. Furthermore, reference counting isn’t able release the memory of circularly referenced objects. Objects in reference counting also have to keep track of variables that weakly reference them, to reassign them to nil/null when the object is deallocated. Lastly, dealing with the reference counters in multithreaded programs with shared memory also becomes a challenge since the reference counter modifications need to be atomic operations.

Python’s reference implementation CPython also uses reference counting, with the addition of tracing garbage collection. Tracing garbage collection periodically pauses the program to count the objects that are reachable from the root object, collecting the unreachable ones.

The advantage with tracing garbage collection is that circularly referenced objects can automatically be deallocated by the interpreter. However, it also makes the program less suitable for real-time applications, since it regularly needs to be paused for the garbage collection to take place.

Read more on: