How does the .NET garbage collector decide what to collect, and how would you make a hot path allocate less?
Answer
Short answer
The GC segregates the heap into generations on the assumption that most objects die young, collecting gen0 often and gen2 rarely, with large objects on a separate heap that is not compacted by default.
Keep garbage collection explicit in the answer because that is the concept the interviewer is actually trying to test. A good garbage collection explanation names the trade-off, the failure mode, and the evidence you would use before choosing. Use garbage collection once more at the decision point so the answer reads as judgement rather than a detached example.
Keep garbage collection explicit in the answer because that is the concept the interviewer is actually trying to test. A good garbage collection explanation names the trade-off, the failure mode, and the evidence you would use before choosing.
Was this answer helpful?
Likely follow-ups
- Why does the GC need a write barrier, and what would break without one?
- Your service shows steadily rising memory with no gen2 growth. Where do you look?
- When is ArrayPool<T> the wrong answer?
- Why can a Span<T> not be a field of a class or live across an await?
Related questions
- A hot path allocates heavily and garbage collection is showing up in your profile. What does Span give you that a substring does not?hardAlso on span and memory4 min
- Memory keeps climbing in a Go service under load. How do you find out why, and what can you actually tune?hardAlso on garbage-collection and memory6 min
- A long-running Python service keeps climbing in memory and never comes back down. How do you work out where the memory went?hardAlso on memory and garbage-collection5 min
- What happens when you append to a slice, and when do two slices stop sharing memory?mediumAlso on memory and garbage-collection5 min