How Garbage Collection Works
How your language frees memory you forgot to.
In managed languages you allocate memory but rarely free it. A garbage collector figures out which objects are still reachable and reclaims the rest — automatically, while your program runs.
Legend — how to read this diagram
Finding what's garbage
- Roots. Start from things definitely alive: globals, stack variables, CPU registers.
- Mark. Follow every reference from the roots, marking each object you can reach.
- Sweep. Anything unmarked is unreachable — free it.
- Compact (optional). Slide survivors together to defragment and speed future allocation.
Why generational GC is common
Most objects die young. So collect the young generation often and cheaply.
Promote survivors. Objects that live long move to an old generation collected rarely.
Pauses vs throughput. Concurrent collectors trade a bit of speed for shorter pauses.
If nothing can reach an object, the program can never use it again — so it's safe to reclaim.
No comments:
Post a Comment