Ideally you should not have to call the Garbage Collector in .net code and this exactly what many online resources claim. .Net garbage collector works with generations. When an object is allocated it is of generation 0 and the more (garbage) collects it survives the higher the generation (currently only generations 0, 1 and 2 exist) becomes. During a collect objects of the relevant generation are checked and released if unreferenced.
Thus calling an unnecessary GC.Collect will increase the generation and even prevent the fast release of objects.

The CLR will call GC.Collect(0) frequently and GC.Collect(2) rarely.

When working with map themes and large grid coverages in DelftShell we noticed an unnecessary long survival for unused objects. Apparently this is caused by the following scenario:
-allocate large object
-perform time consuming algorithm (generation of object will increase)
-dereference object

the default GC.Collect(0) will fail because large object is of generation 1 or even 2.
In this case it is useful to call GC.Collect() (=GC.Collect(2))

References:

Rico Mariani's Performance Tidbits

When to call GC.Collect() http://blogs.msdn.com/ricom/archive/2004/11/29/271829.aspx

Two things to avoid for better memory usage http://blogs.msdn.com/ricom/archive/2003/12/02/40780.aspx

Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

Garbage Collection Part 2: Automatic Memory Management in the Microsoft .NET Framework http://msdn.microsoft.com/en-us/magazine/bb985011.aspx

  • No labels