Garbage Collection
Automatic memory management that reclaims memory no longer reachable by the program, eliminating manual deallocation and its associated bugs.
Garbage collection (GC) is automatic memory management: a runtime component identifies memory that the program can no longer reach and reclaims it for reuse. Languages such as Java, Go, Python, JavaScript, and Ruby rely on it so that programmers never call free() or delete explicitly. This eliminates two whole classes of manual-memory bugs — use-after-free and memory leaks — at the cost of some runtime overhead and unpredictable pauses.
Tracing collectors determine liveness from the set of root references (global variables, stack frames, registers) and walk the object graph: anything reachable from a root is alive, everything else is garbage. Mark-sweep first marks reachable objects then sweeps the heap; mark-compact additionally moves survivors together to fight fragmentation; copying collectors split the heap into two semispaces and copy survivors back and forth. Most modern collectors are generational: they exploit the empirical observation that most objects die young, so the collector scans the small young generation frequently and the large old generation rarely. This is why short-lived temporary objects in Java or C# are cheap.
Reference counting is the main alternative: every object stores a count of incoming references, and when the count reaches zero the object is freed immediately. It is simple and has no global pauses, which is why Swift, Objective-C, and PHP use it — but it cannot collect reference cycles (two objects that point only at each other), so cycle-breaking machinery is needed. Python combines reference counting with a cycle detector for the same reason.
GC interacts with performance in subtle ways: allocation is usually cheap (bump-pointer allocation), but collection pauses, cache behavior during compaction, and memory overhead must be tuned. Real-time and embedded systems often avoid GC for deterministic latency. Rust takes the opposite design point: ownership and borrowing rules give Rust the safety of GC without a garbage collector at all, by making memory lifetimes a compile-time property — the two approaches are the standard modern contrast in memory management design.
Tags
compilers memory management programming runtime systems
Related articles
Click here for easy-to-read helpful e-books for anyone, anywhere, and about anything