What is the role of garbage collector in .NET?

Objects created are stored on heap. Since the memory (here heap) is exhaustible, .NET identifies a mechanism to collect the unused memory(heap). GC does an automatic sweep of heap once it is full. GC can only destroy managed objects.

GC will finalize all the objects in the memory that are not being used anymore and thereby freeing the memory allocated to them.

.NET uses a three-generation approach to collecting memory. Newly allocated memory tends to be freed more frequently than older allocations, which tend to be more permanent. Gen 0 (Zero) is the youngest generation and, after a garbage collection, any survivors go on to Gen 1. Likewise, any survivors of a Gen 1 collection go on to Gen 2. Usually garbage collection will occur only on Gen 0, and only if after it has reached some limit. Until memory is exhausted, the cost of allocating each new object is that of incrementing a pointer–which is close to the performance of advancing the stack pointer.

CLR calls the GC when there is a high memory pressure and it is not able to find any exact place to allocate a new object or the applied threshold is reached.
Tags:
Hot on Web:


About author