What is Garbage Collector?

0 votes
42 views
Shivam Prajapati asked 27 days ago in programming by Shivam Prajapati

What is Garbage Collector with example?        

1 Answer

0 votes
Ravi Vishwakarma answered 26 days ago by Ravi Vishwakarma
Garbage collection
 Automatic memory management possible in .NET Framework. When we create reference type variable or value type variable in .NET Framework then create space in memory in ram. If we create the value type variable then space created in stack memory and reference type variable create then space create in heap memory. In this case garbage collection is very useful as it automatically release the memory after no longer used in application.
How it occur
  1. if the system has low physical memory
  2. If the memory allocate to various object in heap memory exceed then garbage collection occur
  3. if the GC.Collect method is call then garbage collection in occur. However, this method is only called under unusual situations as normally garbage collector runs automatically.
Generation in garbage collector
 The heap memory is organized into 3 generations so that various objects with different lifetimes can be handled appropriately during garbage collection. If the any object goes to generation 0 then .net release these object from memory.
  1. Generation 0
  2. Generation 1
  3. Generation 2

Generation 0 :
 All the short-lived objects such as temporary variables are contained in the generation 0 of the heap memory. All the newly allocated objects are also generation 0 .
 Generation 1 :
 If space occupied by some generation 0 objects that are not released in a garbage collection run, then these objects get moved to generation 1. The objects in this generation are a sort of buffer between the short-lived objects in generation 0 and the long-lived objects in generation 2.
Generation 2 :
 If space occupied by some generation 1 objects that are not released in the next garbage collection run, then these objects get moved to generation 2. The objects in generation 2 are long lived such as static objects as they remain in the heap memory for the whole process duration.