EMZETT.
Login

Garbage collection algorithms

In short: A garbage collector automatically frees the memory of no-longer-reachable objects. Methods are reference counting, mark-and-sweep and generational collectors.

In more detail: Objects that the program can no longer reach count as garbage. The collector finds them by marking all reachable objects starting from “roots” (stack, global variables). The rest is freed. This saves manual memory management but costs run time and can cause pauses.

In Depth

  • Reference counting: Each object counts references. Simple, fails on cycles (Python adds cycle detection).
  • Mark-and-sweep: Mark, then collect. Can fragment.
  • Copying collectors: Copy live objects to a new area, compacts automatically.
  • Generational collection: Most objects die young, so often only the young generation is checked.
  • Stop-the-world: The program pauses. Modern collectors (G1, ZGC, Go) work concurrently with short pauses.
  • Alternative: Ownership models (Rust ownership) without a run-time collector.
  • Memory leaks despite GC: Unintentionally held references (caches, listeners).

See also: Type systems and type inference, Virtual memory and paging