Fundamentals · Hard · Free
What is garbage collection? How do reference counting and mark-and-sweep differ?
FresherFundamentalsProgramming Fundamentals
Garbage collection
Garbage collection (GC) reclaims heap memory for objects no longer reachable from GC roots (stack locals, static fields). The mutator (your code) allocates; the collector traces live objects and frees the rest.
| Approach | Idea | Trade-off |
|---|---|---|
| Reference counting | Free when count hits 0 | Cycles leak unless handled |
| Mark-and-sweep | Mark reachable, sweep rest | Pause times; needs compaction |
| Generational | Young gen collected often | Assumes most objects die young |
diagram
roots → mark live objects on heap → sweep unmarked → (optional) compactMention stop-the-world pauses and that GC languages still leak via static caches, listeners, and unclosed resources.