The general advise is that you should not call GC.Collect
from your code, but what are the exceptions to this rule?
I can only think of a few very speci
I use GC.Collect
only when writing crude performance/profiler test rigs; i.e. I have two (or more) blocks of code to test - something like:
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
TestA(); // may allocate lots of transient objects
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
TestB(); // may allocate lots of transient objects
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
...
So that TestA()
and TestB()
run with as similar state as possible - i.e. TestB()
doesn't get hammered just because TestA
left it very close to the tipping point.
A classic example would be a simple console exe (a Main
method sort-enough to be posted here for example), that shows the difference between looped string concatenation and StringBuilder
.
If I need something precise, then this would be two completely independent tests - but often this is enough if we just want to minimize (or normalize) the GC during the tests to get a rough feel for the behaviour.
During production code? I have yet to use it ;-p