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:
- The Finalizer execution is non deterministic – it depends on GC and the way it’s operating: concurrent or synchronous.
- It requires two GC cycles to completely remove the object and memory footprint.
- 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:
- Implement System.IDisposable interface
- move Finalizer code to Dispose method
- 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.
- 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.