.NET – The Garbage Collector and Finalizers

I’m not used to use Finalizers in my everyday job but I always thought that if I use it more frequently I could achieve some extra performance.

Well, I’m a natural lazy programmer and that prevents me from digging deeper and doing some tests to clarify this guess.

Thanks to community, there is always someone ready to share knowledge and help those lazy guys like me.

One of those guys were Andrew Hunter that posted an article named “Understanding Garbage Collection in .NET”.

In is article I found that:

  • 1. The Finalizer execution is non deterministic – it depends on GC and the way it’s operating: concurrent or 2. synchronous.
  • 3. It requires two GC cycles to completely remove the object and memory footprint.
  • 4. Two many objects with Finalizers could slow down GC a lot

This don’t mean that we shouldn’t use Finalizers, but we must take same care when we create Finalizers. The simplified way to Finalizer usage is:

  1. a) Implement System.IDisposable interface
  2. b) move Finalizer code to Dispose method
  3. c) Finish Dispose method execution with a GC.SupressFinalize() operation, this way the GC will know that this object wont need the Finalizer invocation and can be remove immediately.
  4. d) Invoke Dispose method in Finalizer – this way we ensure that external resources were always removed.

A deeper understand on this procedure, also known as the IDisposable Pattern, can be acquired by reading this article (kindly pointed by Luis Abreu).

Conclusion

Using finalizers don’t bring any performance improvement but it’s wrong use can be a vector for severe memory management problems.

When we have a class that own external reference not managed automatically by Runtime then the IDisposable Pattern should be used to ensure the correct memory cleanup.

One thought on “.NET – The Garbage Collector and Finalizers”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>