/ˈɡɑːrbɪdʒ kəˈlɛkʃən/
noun … “Automatic memory reclamation.”
Garbage Collection is a runtime process in programming languages that automatically identifies and reclaims memory occupied by objects that are no longer reachable or needed by a program. This eliminates the need for manual deallocation and reduces memory leaks, particularly in managed languages like Java, C#, and Python. Garbage collection works closely with heap memory, tracking allocations and references to determine which memory blocks can be safely freed.
Key characteristics of Garbage Collection include:
- Automatic reclamation: memory is freed without explicit instructions from the programmer.
- Reachability analysis: objects are considered “garbage” if there are no references from live code.
- Strategies: multiple algorithms exist, such as reference counting, mark-and-sweep, generational, and incremental collection.
- Performance impact: garbage collection introduces overhead, often mitigated by optimizing collection frequency or using concurrent collectors.
- Interaction with heap: works on dynamically allocated memory, ensuring efficient memory usage and reducing fragmentation.
Workflow example: In Java-like pseudocode:
function main() {
obj = new Object() -- Allocate memory on heap
obj = null -- Remove reference
-- Garbage collector identifies obj as unreachable and frees its memory
}Here, once obj has no remaining references, the garbage collector can reclaim the memory automatically, preventing leaks and optimizing resource usage.
Conceptually, Garbage Collection is like a janitor in a library who periodically removes books that are no longer referenced or in use, ensuring the shelves (heap) remain organized and available for new material.
See Heap, Memory Management, Memory, Reference Counting, Stack.