Crafting Interpreters · Week 14
Crafting Interpreters 26: Garbage Collection: reading guide
Read the chapterVerified by tests
A mark-sweep garbage collector: roots, marking with a gray stack (tricolor abstraction), tracing references, sweeping unreachable objects, weak references for the string table, and when to trigger collection.
Time About 8 hours this week
Why it matters
GC is one of the most misunderstood parts of every runtime. After this, Java, Go and JavaScript GC logs make sense, and Knuth 2.3.5 will feel familiar.
How to approach it
Enable the stress-GC mode (collect on every allocation) and the GC log as the book suggests. Most bugs only show up under stress mode.
Challenges
3 challenges at the end of the chapter.
Challenge 1 (shrink the object header) and challenge 2 (avoid clearing mark bits on every sweep) are good optimizations. Challenge 3 (try another GC algorithm) is a big project; save it for after the book.
Traps
- An object allocated but not yet reachable gets collected mid-operation. Push temporaries on the stack before allocating again.
- Forgetting to mark compiler roots while compiling.
- Not removing unmarked strings from the intern table before sweeping.
Verified by the book's chap26_garbage tests when you push your repo.