Friday 11 April 2014

Garbage Collector

The Garbage Collector is a special feature of C# that automatically clears objects from memory when they are no longer needed. For example: once a method is finished executing, the garbage collector removes any variables it used from the memory. Thanks to the garbage collector it is very rare for C# applications to suffer from memory leak issues when the program uses up more and more memory until it overloads the system.

The garbage collector will work automatically without you needing to do anything but you can send commands to it by using the GC class. The GC class can also provide some useful information about memory usage.
It is important to note that using the GC class can potentially make your project less memory efficient. The garbage collector files your objects into one of three categories or generations.

Generation 0 contains objects that will be disposed off quickly such as variables within methods. Generation 1 contain objects that are expected to remain in memory for longer, a public property of a class might be a generation 1 object. Generation 2 contains objects that are expected to remain in memory for a very long time such as static classes.

When the garbage collector cleans up memory, it promotes any object that is still in use to the next generation. Misusing the GC class can lead to objects being promoted to inappropriate generations and remaining in memory for longer than they should.

No comments:

Post a Comment