Let’s dive into the world of garbage collection (GC) in .NET. The garbage collector is a crucial component that manages memory allocation and reclaims memory for your application. Here’s a comprehensive overview:
Garbage Collection Basics:
- The garbage collector automatically handles memory management, freeing developers from manual memory release tasks.
- When you create an object using
new
, the runtime allocates memory for it from the managed heap. - As long as address space is available in the managed heap, the runtime continues allocating space for new objects.
- Eventually, the garbage collector performs a collection to free memory by reclaiming unused objects.
Generational Garbage Collection:
- The GC divides objects into three generations: Gen 0, Gen 1, and Gen 2.
- Most objects die quickly (short-lived) in Gen 0 (e.g., request-scoped objects in a server app).
- Gen 1 acts as a buffer between young and long-lived objects.
- Gen 2 contains long-lived objects.
- Gen 2 collections are also called full GCs.
Stages of Garbage Collection:
- Marking Phase:
- Identifies live objects by creating a list of them.
- Relocating Phase:
- Updates references to objects that will be compacted.
- Compacting Phase:
- Reclaims memory occupied by dead objects and compacts surviving objects.
- Marking Phase:
Types of Garbage Collection:
- Workstation GC:
- Optimized for desktop applications.
- Runs on a normal priority thread.
- Server GC:
- Default for ASP.NET Core apps.
- Optimized for servers.
- Creates a separate managed heap and GC thread per logical CPU.
- Workstation GC:
Large Object Heap (LOH):
- Definition: Objects greater than or equal to 85,000 bytes are considered large objects.
- Placement: Large objects go on the LOH (sometimes called Gen 3).
- Collection: Collected only during Gen 2 collections (full GCs).
- Performance Implications:
- Compacting large objects can be expensive.
- LOH memory is usually not compacted to avoid moving large objects.
- LOH is separate from the small object heap (SOH).
Size Threshold for LOH:
- Any object allocation request for 85,000 bytes or more goes to the LOH.
- This threshold was determined through performance tuning.