What’s so wrong about using GC.Collect()?

From Rico’s Blog…

Rule #1

Don’t.

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 orginal posting so I won’t repeat
all that here. So let’s move on to…

Rule #2

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

A classic example of this is if you’re
writing a client application and you
display a very large and complicated
form that has a lot of data associated
with it. Your user has just
interacted with this form potentially
creating some large objects… things
like XML documents, or a large DataSet
or two. When the form closes these
objects are dead and so GC.Collect()
will reclaim the memory associated
with them…

So it sounds like this situation may fall under Rule #2, you know that there’s a moment in time where a lot of old objects have died, and it’s non-recurring. However, don’t forget Rico’s parting words.

Rule #1 should trump Rule #2 without
strong evidence.

Measure, measure, measure.

Leave a Comment