Garbage Collection is the process of automatically freeing memory by removing objects that are no longer accessible by any part of the program. This ensures that unused objects do not consume memory indefinitely.
If no variable holds a reference to an object, that object becomes eligible for garbage collection.
Note:
Garbage Collector (GC), a component of the Common Language Runtime (CLR) automatically reclaims memory occupied by objects that are no longer in use, so developers don’t need to manually free memory as in languages like C or C++
Features of Garbage Collection
Automatic memory management: no need for explicit free() or delete.
Optimized allocation: memory is managed in generations for better performance.
Prevents memory leaks: unused objects are removed.
Non-deterministic: the exact time of collection is not predictable.
Generations in Garbage Collection
To improve performance, the Garbage Collector (GC) organizes objects in the heap into generations. This strategy is based on the observation that most objects are short-lived, while a smaller portion live longer.
Examples include local variables, temporary objects like strings created inside a loop or lightweight helper objects.
Since most objects die quickly, GC frequently collects Generation 0, reclaiming memory immediately.
Objects that survive this collection are promoted to Generation 1.
Generation 1 (Survivors of Gen 0 Collection)
Acts as a buffer zone between short-lived and long-lived objects.
If an object survives one or more GC cycles in Generation 0, it is promoted here.
This generation is collected less often than Generation 0, balancing performance and memory use.
Typical objects in Gen 1 are those used beyond a single method call but not throughout the application’s lifetime.
Generation 2 (Long-Lived Objects)
Contains objects that survived multiple collections.
These are usually long-lived objects, such as static data, application caches or large objects that persist for the lifetime of the program.
Collected least frequently because scanning this region is expensive.
The runtime delays cleaning Gen 2 objects unless memory pressure is high.
Phases of Garbage Collection in C#
Example: Count of the number of Generations.
Phases in Garbage Collection
Garbage collection runs in phases to clean memory in an organized and efficient way. These phases ensure that unused memory is reclaimed, references are updated and fragmentation is reduced.