Please don’t call GC.Collect()

The thing with quasi-religious beliefs is that they tend to repeatedly come up throughout the circle of life.

Just recently, I reviewed a  friend’s code where he implemented the Dispose Pattern horribly wrong, involving a call to GC.Collect().

And today, a coworker on an internal distribution list refers to Rico Mariani’s "When to call GC.Collect()" post from 2004, and, in particular, at the comments to that post, indicating there could be something complicated or unresolved in this matter.

To me, it’s quite simple.

To avoid manifestation of superstitious rituals, let me quote Rico’s main rules (emphasis mine):

Rule #1


This is really the most important rule.  It’s fair to say that most usages of GC.Collect() are a bad idea and I went into that in some detail in the original posting so I won’t repeat all that here.  So let’s move on to…

Rule #2

Consider calling GC.Collect() [only] if some non-recurring event has just happened and this event is highly likely to have caused a lot of old objects to die.

In addition, let me also quote from the memory usage post Rico refers to in the first paragraph:

Almost-rule #1: Never call GC.Collect()

If you think you need to force a collection something has gone very wrong. You have to ask yourself, what sort of collection do I think I need? Gen0, Gen1, Gen2? How do I know that the GC will decide to do the collection that I think I need? What did I do so that now I need that kind of collection?

And, while we’re at it:

Almost-rule #2: Never have finalizers
(except on leaf objects which hold a single unmanaged resource and nothing else)

Checking in code using GC.Collect() should be allowed only after providing strong evidence and after several rounds of code review.

Calling GC.Collect() is no workaround for anything, even less a fix. And when you start using GC.WaitForPendingFinalizers() you need code review and counseling. Seriously.

And never, never, never call GC.Collect in the Dispose method. Never. This is like trying to empty a waste bin with a stick of Dynamite.

Please, don’t call GC.Collect(). Help Make Software Better.™

Just my 2¢ after reading the garbage collection post and the comments, especially contrasting those from Darren Oakey and Ian Griffiths.

This entry was posted in Coding Horror. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s