Garbage Collection in .NET

Garbage Collection in .NET

Garbage Collector provide automatic Memory Management in .NET. It is Component of .net CLR (Common Language Runtime). Follow are the advantages of Garbage Collection –

  • It allocates memory objects on heap efficiently.
  • Develop application without worrying about releasing of memory.
  • Reclaims object that are no longer in use, clear their memory and keep it available for future memory allocations.
  • Memory Safe as cannot direct access memory of other objects.

Fundamentals of Memory –

  • Each process has its own, separate virtual address space; on 32-bit computers each process has a 2-GB user-mode virtual address space.
  • Garbage collector is responsible for Allocation and frees virtual memory on Managed Heap.
  • Virtual memory can be in three state – FREE , RESERVED, COMMITTED
  • We can run out of memory if run out of virtual address space to reserve or physical space to commit.

When Garbage Collection runs-

  • System has low physical memory
  • The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This means that a threshold of acceptable memory usage has been exceeded on the managed heap. This threshold is continuously adjusted as the process runs.
  • The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

What is Managed Heap?

  • Garbage Collector allocates segment of memory for objects which is called Managed Heap.
  • Each managed process has managed heap.
  • Win32 VirtualAlloc and VirtualFree functions called by garbage collector to reserve or release segment of memory.
  • After triggering Garbage Collector, it reclaims the memory occupied by dead objects and compact live objects so they live together. This process will make heap smaller.
  • Heap can be considered as : Large Object Heap and Small Object Heap
  • Objects with size 85000 bytes and larger will go on Large Object Heap.

Generations

  • Heap is organized into generations which can easily handle long live objects and short lived objects.
  • There are three generations – Generation 0 , Generation 1, Generation 2
  • Generation 0 – This is youngest generation for newly created objects. Garbage collector reclaims memory from this Generation most frequently. For e.g. Temporary variables, new objects
  • Generation 1 – Short lived objects are resides in this generation. As soon as Garbage collector starts reclaiming memory, objects from Generation 0 will move to Generation 1 if they are still in use.
  • Generation 2 – Long lived objects are resides in this generation. For e.g. Static variables.

You can find detailed article on – http://msdn.microsoft.com/en-us/library/ee787088.aspx