Computer ScienceProgrammingMedium

Garbage Collection

Also known as:automatic memory managementGCautomatic garbage collection

Garbage collection (GC) is an automatic memory management process that reclaims heap memory occupied by objects no longer reachable or needed by a program. By tracking object references and periodically freeing unreachable memory, GC eliminates common bugs such as memory leaks and dangling pointers without requiring explicit deallocation by the programmer. It is a core feature of languages including Java, Python, Go, C#, and JavaScript, with algorithms such as mark-and-sweep, reference counting, and generational collection.

Common Garbage Collection Algorithms Compared

AlgorithmHow It WorksPause TimeLanguage Examples
Reference CountingTracks refs to each object; frees at zeroLow (incremental)Python (CPython), Swift
Mark-and-SweepMarks reachable objects; sweeps unmarkedStop-the-world pausesEarly Java, Go
Generational GCSeparates objects by age; collects young oftenLow for young genJava (JVM), .NET CLR
Tri-colour MarkingConcurrent mark using white/grey/black setsVery lowGo (post-1.5), V8
Compacting GCMoves surviving objects to eliminate fragmentationModerate pauseJava G1, .NET

Interactive Tools

Codecademy – Java Memory

Open Tool

Brilliant – Algorithms

Open Tool

Khan Academy – Computer Science

Open Tool
Animation of mark-and-sweep garbage collection algorithm traversing object graph

Wikimedia Commons, CC BY-SA

Related Terms

The term "garbage collection" was coined by John McCarthy in 1959 during the development of LISP, where he used the metaphor of collecting unused memory "garbage" to reclaim storage for reuse.

garbage-collectionmemory-managementjavamark-and-sweepruntime