To make garbage collection faster and more efficient, the .NET Heap is divided into three generations:
Generation 0 (Gen 0) – Short-Lived Objects
- Stores newly created objects.
- It is collected frequently, as most objects are temporary (e.g., loop variables).(These are usually temporary variables, method-level objects, etc)
- Gen 0 is collected most frequently, and collection here is very fast.
- If an object survives GC in Gen 0, it is promoted to Gen 1.
Example: A temporary list used inside a method. Loop variables or temporary string objects.
Generation 1 (Gen 1) – Medium-Lived Objects
- Objects that survive Gen 0 (still being used) are moved to Gen 1. Acts as a bridge between Gen 0 and Gen 2.
- Holds objects that survived Gen 0 GC.
- These are not temporary, but not long-term either.
- Acts as a buffer zone between short-term and long-term memory.
- Collected less often than Gen 0.
- If an object in Gen 1 still survives GC, it is promoted to Gen 2.
Example: An object used throughout a single operation or request. Objects used during an entire transaction or user request.
Generation 2 (Gen 2) – Long-Lived Objects
- Objects that survive multiple garbage collections are moved here
- These are long-lived objects,like static data, global caches, etc.
- Collection is slow and expensive, so GC avoids collecting Gen 2 unless really needed.
Example: Static data, cached objects, or global settings used throughout the app.
Important Notes:
Gen 2 collection is a full GC, meaning it also collects Gen 1 and Gen 0.
Memory size:
➤ Gen 2 > Gen 1 > Gen 0(More memory is given to older generations)
The .NET GC engine automatically promotes objects from one generation to the next based on their lifespan and usage.