Garbage collection - automatically freeing up memory space that is no longer used by objects.

In C, one takes care of memory allocation and deallocation using malloc() and dealloc() functions. In most high-level languages, this is handled by default.

Types

Reference counting

Used by Python (with a cycle-detection algorithm), Swift.

Tracks the nr of references for each object. If it reaches 0, it is marked for collection.

It struggles when objects reference each other circularly.

Mark and sweep

Used by JavaScript, Java.

Phases:

  1. Mark: The garbage collector traverses the entire memory space, marking all objects reachable from the program’s root (e.g., global variables).
  2. Sweep Phase: It sweeps through memory, freeing any objects that were not marked, signifying they are unreachable.

More efficient than reference counting.

Generational Garbage Collection

Divides objects into generations based on their age. Newer objects reside in younger generations, and older objects are in older generations.

Sources