Just Say No to Finalization!

I am working with some classes that wrap unmanaged APIs, so I have to be concerned with releasing the resources associated with these APIs-- eg, the IDisposable interface. I was a little confused about the distinction between Dispose() and Finalize(), and in my research I found this article by Brent Rector of Wintellect:

This is a companion discussion topic for the original blog entry at: http://www.codinghorror.com/blog/2004/07/just-say-no-to-finalization.html

Jeffrey Richter’s “Applied Microsoft .NET Framework Programming” has a very good treatment of this issue.

Here’s my two-pennorth:

Sure, there’s an overhead attached to stuff that does finalization, but you can see in your sample dispose method how it’s dealt with. When you explicitly call your dispose method, you clean up your resources, and then suppress finalization, thereby clawing back most of your Finalize-caused performance drop.

I suppose the allocation of a finalizable object is slower than for a non-finalizable object, but that’s because for the non-finalizable object, allocation is just incrementing a pointer. OK - can’t get much faster than that, but who cares? If you’ve got a bunch of external resources to get started up anyway, there’s not much point in discussing the theoretical possiblity of a “for free” allocation.

I actually own that book, and I’ve never gotten around to reading it. I’ll check that section out. Jeffrey Richter, what the hell does that guy know anyway? :wink:

I think, in general, one should avoid implementing IDisposable unless you have to. According to Paul Wilson, the dataset implements IDisposable, but ONLY because of some freakish side effect of inheritance-- in other words, it doesn’t actually do anything useful in the finalization, which sort of devalues the rule “if implemented, must use”