The process of releasing memory objects which are no longer used by an application in a .Net environment is known as Garbage collection. Garbage collector helps the CLR to perform better memory management.
How garbage collector works.
Garbage collector uses a managed heap to store objects. Newly created object will be at the top of the heap (higher memory addresses) and older objects will be at the bottom.
Based on the age of memory objects, garbage collector group objects into to three different groups which are generally known as generations. There will be 3 different generations. Generation 0, Generation 1, Generation 2
Generation 0 – All the newly created objects will be in Generation 0. After a period of time objects which are still alive in Gen 0 will be moved to Generation 1.
Generation 1 (Gen1) – All the objects which were in Gen 0 and have survived a series of garbage collection will be moved to Gen 1
Generation 2 (Gen 2) – Objects like global variables, static variables will be usually be in Gen 3 because they will be alive till the application runs.
Collecting the Garbage
During a GC operation CLR will pause the application execution
There are two types of collection
1) Partial collection – It is considered to a very cheap operation. Only objects in Gen 0 will be released
2) Full collection – GC will perform this operation in all generations and it is considered to a an expensive operation
After this process dead objects will be removed from the heap and live objects will be rearranged to fill the gaps. Generations also will be updated after this process