Performance Penalty for Finalizer If Never Called

979 Views Asked by At

I have a class with a finalizer. But since I'm always calling Dispose() and Dispose() is calling GC.SupressFinalize(this), I think my object never actually makes it into the finalization queue. The finalizer is just in there as a backstop in case another user of the class forgets to call Dispose().

Is there any performance penalty for just implementing a finalizer even if its never called and the object never makes it to the finalization queue?

I used to think not, but on page 102 of Effective C#: Second Edition by Bill Wagner, it says, "Even if it's never called, the presence of a finalizer does introduce a rather large performance penalty for your types."

2

There are 2 best solutions below

1
On BEST ANSWER

Is there any performance penalty for just implementing a finalizer even if its never called and the object never makes it to the finalization queue?

As long as you implement this correctly, and call GC.SuppressFinalize on your object, the "penalty" will only occur when the user does not call Dispose().

That being said, the "severe" penalty is actually not all that severe in most cases. It would be a problem if you had many short lived objects with finalizers polluting your garbage collection process, but that's rarely a problem, since objects with finalizers are rare (overall).

0
On

IIRC, the problem with finalizers is that objects with them survive for an extra gc cycle. This only applies if the finalizer is called, however. This article explains it well: http://anasoft.wordpress.com/2007/06/17/more-about-gc-dispose-and-finalize/