Garbage collection is a runtime memory system that finds objects a program no longer uses and frees their space for new data [6]. American computer scientist John McCarthy invented the method around 1959 to simplify memory handling in Lisp [1]. Today, runtimes for Java, C#, Python, Go, Ruby, and Swift reclaim unused heap blocks on their own while code runs [3]. Because the collector tracks live links during execution, programmers avoid manual free calls at the cost of extra CPU work and periodic pauses [4].
How Does Garbage Collection Work?
A runtime decides which objects to keep by starting from a fixed set of roots and following every pointer chain from there [2]. Microsoft’s .NET documentation lists CPU registers, GC handles, static fields, the finalize queue, and local stack variables on each thread as those starting points [4]. Any object reachable from a root, either right away or through another live object, stays in memory, while everything outside that graph becomes eligible for reclamation. In languages that mix object references with unboxed values on the stack, the collector relies on tools like tagged pointers so it won’t mistake a plain integer for a memory address [2].
Researchers split unreachable data into syntactic garbage, which a program has no path left to reach, and semantic garbage, which a program can still reach but will never read again. Proving whether an arbitrary program will read an object later reduces to the halting problem, so practical runtimes collect syntactic garbage [2]. Once a collector clears dead blocks, it sometimes shifts surviving objects in memory to cut down on heap fragmentation [7].
In A Unified Theory of Garbage Collection, Bacon and co-authors showed that tracing and reference counting are mathematical duals. Tracing follows live pointers from roots to count reachable objects, while reference counting tracks incoming pointer updates to spot dead ones. Every working collector blends both methods across unified, split, or multi-heap layouts [7].

Manual Memory Risks
Languages such as C and C++ leave heap management to the coder through explicit calls like malloc() and free() [9]. Forgetting to release an unused block causes a memory leak that can use up all RAM and crash both the program and the host machine. Freeing a block too early creates a dangling pointer if another variable still holds its address, and freeing the same address twice can crash the memory manager. Martin Heller noted in InfoWorld that buffer overruns and string bugs in C and C++ can even let attackers overwrite code with executable data [3].
Automatic management changes how new objects enter memory as well as how old ones leave. In C, the allocator walks free-list structures built on linked-list concepts to find an open gap that fits the requested object size [9]. In .NET, the CLR reserves a contiguous virtual address region called the managed heap and places each new reference type right after the last one by advancing a pointer. That bump-pointer approach makes creating managed objects nearly as fast as pushing data onto a call stack [4].
Managed objects also start with clean zeroed bytes, so constructors in C# don’t have to wipe every field to avoid reading leftover memory. Because the .NET CLR fences off each object’s space, one object can’t touch memory owned by another, though callers can still force a pass with GC.Collect [4].
Tracing Collectors
Tracing is so common that many engineers simply call it garbage collection, and its baseline form is the naïve mark-and-sweep algorithm published in 1960. A stop-the-world mark-and-sweep pass freezes the running program, walks every pointer from the roots to flag live blocks as in-use, and sweeps the heap to free everything else [3]. Simple stop-the-world pauses break real-time guarantees, so interactive software relies on incremental steps [8].
Incremental collectors interleave collection with the running program, called the mutator, using a tri-color marking scheme made of white, gray, and black sets [8]. At the start of a cycle, objects referenced by roots turn gray while all others sit in the white set. The collector moves each gray object to black after coloring its child references gray, then frees any white blocks left when the gray set empties [3]. If the mutator swaps pointers mid-cycle so a black object points to a white one and drops the old link, a read or write barrier must catch the change before live data gets freed. Wyatt Gaswick reported in a 1999 Grinnell College presentation that read barriers often add tens of percent in overhead because heap reads outnumber heap writes [8].

Copying collectors like Cheney’s algorithm split memory into two equal halves called from-space and to-space and move live objects into the clean half when space fills up [3, 8]. Copying runs fast when most objects are dead, but it needs twice the memory and forwarding tables because object addresses change. Mark-and-compact collectors avoid that double memory cost by sliding live objects down inside one heap, though compacting takes more CPU time [3].
Reference Counting
Reference counting stores a counter for each object, often a 32-bit or 64-bit unsigned integer in a header, and changes that number whenever a pointer is copied or cleared [1, 5]. When an object’s count hits zero, the runtime frees the block right away without pausing a program for a full heap scan [5]. On 64-bit ARM64 chips running iOS 7, Apple saved header bytes in Objective-C by packing the count into 19 unused bits of each object’s class pointer [1]. Objects that hold files or locks also run their destructors as soon as their last link drops [5].
Two flaws hold back simple reference counting: pointer cycles and update costs [3]. If Object A points to Object B and Object B points back, neither count ever hits zero after the program drops both [5]. PHP 5.3 added a cycle collector with a 10,000-entry root buffer to clear those loops. In a PHP manual test running one million self-referencing objects, turning on cycle collection cut peak memory by 98%, from 931Mb down to 10Mb, while slowing runtime from 10.7 seconds to 11.4 seconds, a 7% hit. The collector ran 110 times and freed over two million allocations during that test [10].
Frequent pointer writes also slow multithreaded code, which must guard counters with atomic locks like Win32 InterlockedIncrement or compare-and-swap, though Linux kernel modules use per-CPU counters to avoid global locks [1, 5]. C++ smart pointers pass links by const reference so functions skip extra counter bumps. Deutsch-Bobrow collection ignores local stack updates until deletion, and Levanoni and Petrank’s update coalescing cut over 99% of counter updates in Java tests [1].

Generational Garbage Collection
Most objects die soon after creation, so generational garbage collection groups allocations by age instead of scanning the entire heap on every pass [6]. Temporary variables rarely survive one cycle in .NET or Java, while long-lived data stays untouched so compacting young regions takes far less time [4].
Microsoft’s .NET CLR splits its small object heap into generations 0, 1, and 2, calling Windows VirtualAlloc to reserve segments and VirtualFree to release empty ones [4]. New objects land in generation 0, survivors move to generation 1, and older survivors enter generation 2 [6]. Objects of 85,000 bytes or more go straight to the Large Object Heap (LOH), which is cleared with generation 2 and usually not compacted to skip copying huge arrays. Collections start when generation 0 fills up, when Windows flags low RAM, or when allocated bytes pass a self-tuning limit [4].
Java splits its heap into a young generation—made of an eden space plus two survivor spaces called S0 and S1—and an old generation called tenured. Java 8 replaced the permanent generation with metaspace, while the JVM supports four options: G1GC by default, plus concurrent mark and sweep, parallel, and serial collectors [3, 6]. CPython pairs reference counting for instant cleanup with a three-generation collector aimed only at container cycles [3].

Weak References and Special Heaps
Ordinary strong references keep an object alive until every path to it vanishes, but programs sometimes need links that read an object without blocking its cleanup. A weak reference lets code inspect a target while it lives and turns safely to null once the collector frees that block, avoiding dangling pointers. Weak hash tables build on this rule by dropping key-value entries on their own when nothing else holds a strong link to the key or value [2].
Runtimes divide weak links into narrower types for caching and cleanup alerts. The JVM offers regular weak references, soft references that hold out until memory grows tight, and phantom references that fire after an object’s finalizer has run. The .NET runtime offers short weak references and long weak references that track resurrection. Unlike managed weak references, an untracked raw pointer left after manual freeing stays dangling and unsafe [2].
Collectors manage heap bytes, not OS handles like network sockets, database connections, windows, or file descriptors, which rely on destructors or close calls. Ada, Modula-3, and C++/CLI support separate heaps for collected and manually freed objects inside one program, while D lets coders delete objects by hand or disable collection for speed. Stack allocation, region inference, and memory ownership models offer other ways to avoid runtime tracing in chosen paths [1].
Performance Costs
Automatic cleanup trades coding ease for extra RAM usage and unpredictable runtime stalls [1, 3]. In a 2005 paper, Matthew Hertz and Emery D. Berger showed that an Appel-style generational collector needs five times as much memory to match oracle-guided explicit deallocation. With three times as much memory, the collector “runs on average 17% slower” than explicit cleanup, and with only twice as much memory it “degrades performance by nearly 70%”. When physical RAM fills up and paging kicks in, collection runs an order of magnitude slower [3].
Server stalls have pushed several infrastructure teams back toward manual languages. Scylla, a C++ rewrite of Cassandra, and Redpanda, a C++ replacement for Kafka, both cut lag and run on smaller server clusters than the original JVM tools [3]. Even inside C++ databases, J. Böttcher, V. Leis, T. Neumann, and A. Kemper reported in Proceedings of the VLDB Endowment in 2019 that coarse background cleanup of Multi-Version Concurrency Control (MVCC) versions stalls mixed HTAP workloads. Their eager pruning method kept overhead low and sped up pure OLTP workloads like TPC-C [14].

Solid-state drives also run their own collection passes because NAND flash blocks must be erased before new writes land [16]. Y. Yang, V. Misra, and D. Rubenstein proved in 2015 that greedy page reclamation minimizes write amplification under memoryless workloads [15]. In 2017, W. Kang, D. Shin, and S. Yoo used reinforcement learning during idle storage windows to cut 99.99th-percentile SSD tail latency by 29% to 36% [16].
Garbage Collection in Practice
Apple’s Mac software offers one of the clearest retreats from tracing garbage collection on desktop systems. Apple added optional GC in OS X 10.5, skipped it on iOS because collector overhead looked too heavy, and launched compiler-based Automatic Reference Counting (ARC) for OS X 10.7 and iOS. Apple marked GC as deprecated in OS X 10.8 and barred new or updated Mac App Store apps from using it starting on May 1, 2015 [12].
C++ followed a similar path at the standards committee level. In 2008, proposal N2670 added minimal garbage collection hooks, including “strict pointer safety” and five library functions, to C++0x. Over the next 12 years, maintainers behind Microsoft’s Standard Library, libstdc++, and libc++ went with relaxed pointer safety instead, while code searches found hits only in GCC and LLVM. In 2021, JF Bastien and Alisdair Meredith wrote in paper P2186R2 that the specification “missed the mark, and will not be missed,” proposing full removal in C++23 [11].
Even without built-in C++ collection, C++ codebases often run collectors for hosted languages: Chromium’s V8 uses Orinoco, Blink uses Oilpan, WebKit’s JavaScriptCore uses Riptide, and Unity pairs C++ with C# over the Boehm-Demers-Weiser Conservative GC (BDWGC) [11]. For tiny 16-bit systems where full BDWGC won’t fit, Ivan Maidanski wrote TinyGC, a single-file stop-the-world collector over malloc() whose binary can shrink to 3,800 bytes. As Maidanski put it on the project site, “TinyGC is NOT designed for speed.” [13]
- WEBSITE Wikipedia. (n.d.). Garbage collection (computer science). Wikipedia. [Article Link]
- WEBSITE Wikipedia. (n.d.). Tracing garbage collection. Wikipedia. [Article Link]
- ONLINE NEWS Heller, M. (2023, February 3). What is garbage collection? Automated memory management for your programs. InfoWorld. [Article Link]
- WEBSITE Microsoft Learn. (2025, October 22). Fundamentals of garbage collection -.NET. Microsoft. [Article Link]
- WEBSITE Microsoft Learn. (2009, January 27). Back to basics: Reference counting garbage collection. Microsoft. [Article Link]
- ONLINE NEWS Sheldon, R. (2022, May 6). Garbage collection (GC). TechTarget. [Article Link]
- WEBSITE Anastos, M., & Huang, Q. (2019, November 8). A unified theory of garbage collection. Cornell University CS 6120. [Article Link]
- WEBSITE Gaswick, W. (1999, October 5). Garbage collection. Grinnell College CS302. [Article Link]
- WEBSITE freeCodeCamp.org. (2020, January 16). A guide to garbage collection in programming. freeCodeCamp. [Article Link]
- WEBSITE PHP Documentation Group. (2018, May 9). PHP: Performance considerations – Manual. PHP.net. [Article Link]
- REPORT Bastien, J., & Meredith, A. (2021, April 16). P2186R2: Removing garbage collection support. ISO/IEC JTC1/SC22/WG21. [Article Link]
- ONLINE NEWS Cichon, W. (2015, February 21). App Store: Apple entfernt Programme mit Garbage Collection. Heise Online. [Article Link]
- WEBSITE Maidanski, I. (2010, January 1). TinyGC. SourceForge. [Article Link]
- ACADEMIC JOURNAL Böttcher, J., Leis, V., Neumann, T., & Kemper, A. (2019). Scalable garbage collection for in-memory MVCC systems. Proceedings of the VLDB Endowment, 13(2), 128-141. [Article Link]
- ACADEMIC JOURNAL Yang, Y., Misra, V., & Rubenstein, D. (2015). On the optimality of greedy garbage collection for SSDs. ACM SIGMETRICS Performance Evaluation Review, 43(2), 63-65. [Article Link]
- ACADEMIC JOURNAL Kang, W., Shin, D., & Yoo, S. (2017). Reinforcement learning-assisted garbage collection to mitigate long-tail latency in SSD. ACM Transactions on Embedded Computing Systems, 16(5s), 1-20. [Article Link]
Cover image: § Music Sorter § / Wikimedia Commons, CC BY-SA 3.0