Joydip Kanjilal
Contributor

Best practices to facilitate garbage collection in .Net

opinion
Sep 25, 20154 mins
Software Development

Take advantage of best practices to facilitate faster and efficient garbage collection in .Net

In Microsoft.Net, garbage collection is a mechanism adopted by the Common Language Runtime (CLR) to clean up the resources consumed by your application. When you create objects in .Net, they are stored in the managed heap. While you need to create objects, in most cases, you don’t have to be worried about cleaning up the objects — the runtime would do it for you.

However, you should adopt best practices in your application to facilitate garbage collection and help it clean up the resources faster. Although .Net is adept at reclaiming managed objects, you should follow certain guidelines to facilitate faster garbage collection to improve the performance of your application. In this article I would like to present a discussion on how garbage collection works and the best practices involved to facilitate garbage collection in .Net.

When does garbage collection take place?

Garbage collection takes place when the system is low on the available physical memory or the GC.Collect() method is called explicitly in your application’s code. Objects that are no longer used or are unreachable from the root are candidates for garbage collection. In essence, the garbage collector cleans up the memory occupied by objects that have no references.

Generations

The runtime organizes the managed heap into generations. It uses these generations to organize short- and long-lived objects. It should be noted that the garbage collector works much more frequently in the lower generations than in the higher ones. Generation 0 contains the short-lived objects such as temporary objects. When an object is created, it is stored in Generation 0 unless it is a large object. If the object is a large object, it is stored in the Large Object Heap (LOH) in Generation 2. In most cases, the Generation 0 objects are reclaimed by the garbage collector when it runs in the background.

When writing code, you should adhere to certain best practices. As an example, you should create objects in the local scope as much as possible to facilitate garbage collection. Objects that are created in the higher scope generally reside in the memory for a longer period of time. You can take advantage of the CLR profiler to understand the allocation patterns of your application.

You should avoid calling the GC.Collect() method as it causes a full collection of all the generations (Generation 0, 1, and 2). When you make a call to the GC.Collect() method, the runtime visits all the live objects in your application. This takes a considerable amount of time and, hence, is a very expensive operation. As a result, it is not a good practice to call the GC.Collect() method.

If you have to call the GC.Collect() method, you should call GC.WaitForPendingFinalizers() after the call to GC.Collect() to ensure that the current executing thread waits till finalizers for all the objects have been executed.

Next, you should make a call to the GC.Collect() method again to ensure that you collect the dead objects that remain. These dead objects that might have been created due to the call to the finalizer method on the objects. The following code snippet shows how these methods are used.

System.GC.Collect();

System.GC.WaitForPendingFinalizers();

System.GC.Collect();

You should ensure that you minimize hidden allocations and write your code in such a way that chances of promotion of short-lived objects to higher generations are eliminated. You should not reference short-lived objects from the long-lived ones to avoid promotion of the short-lived objects to higher generations.

You should also avoid writing finalizers for your classes. If you have a finalizer implemented in your class, objects of such classes would become long-lived objects as the runtime needs to promote the finalizable objects to older generations. You should set objects to null before you make a long-running call if such objects are not needed by the application. If you no longer need a static object or other objects in your application, you should set it to null before making a long running call. You should not set local variables to null as it is not needed; the runtime can determine which local object is not referenced in your code or not used any further, so you need not set any local variable to null explicitly.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author