vote buttons
1
1
beginner
0
intermediate
0
advanced
04-Dec-2014 05:33 UTC
K Bonneau
350

1 Answers

vote buttons
1
What is Garbage Collection
Garbage Collection is a form of automatic memory management. The Garbage Collector gets triggered periodically and tries to reclaim memory occupied by objects that have gone out of scope and can no longer be used by the running application.

When does it get triggered
As per MSDN Garbage Collection gets triggered when any one of the conditions is satisfied:
- The system has low physical memory.
- The allocated memory in the managed heap reaches a particular threshold. (The threshold is not fixed and the runtime keeps adjusting it as the program runs)
- The GC.Collect() function is called. 

The Generations & Heap Compaction
The managed memory area, or the managed heap is divided into 3 areas called generations (+ 1 Large object heap which we will get to later). 
.Net garbage collection and generations
Garbage Collector has to find all orphan allocations, and deallocate them. This deallocation creates gaps in memory where the memory has been freed. So it moves all objects next to each other so no holes remain, and as the objects have been moved in memory all variables pointing to these objects in the program need to be updated so they point to the new location in the memory. 
.Net garbage collection and heap compaction
Garbage collection is an expensive operation, and while the garbage collection runs your application performance suffers. So the garbage collector divides the memory area into generations and whenever the Garbage Collector is required to run, it runs first on Gen 0, and only runs on other generation if it is not able to sufficiently free up memory by collecting objects in prior generations. 
Gen 0 is used for short lived objects as these are the ones which are most likely to be freed up soon. Any object which survives Gen 0 collection (which would mean it is a long lived object) gets promoted to Gen 1 (and similarly from Gen 1 to Gen 2). 

Effect of Finalizers on Garbage Colection
If your class has a finalizer, Garbage Collector needs to run it before destroying the object. As this can take arbitrarily long amount of time, it moves such objects to a special queue called finalization queue. Another thread then executes the finalizers in parallel. This has a very negative impact on GC performance. So we should avoid finalizers in the code. But in some cases we need to clean up some unmanaged resources and we might be forced to write finalizer to ensure unmanaged resources are freed up when the object is destroyed. In such a case you should follow the dispose pattern
04-Dec-2014 05:39 UTC
K Bonneau
350