0

When I'm working with a set of non-struct object-object dictionaries (Dictionary<ClassA,ClassB>) will I do the GC a favor when I call Clear() on all of them?

Or more interresting: Could it do any harm to the GC when I do this?

All objects including the dictionaries are expected to be in generation 2 since it's a long running transformation which will also generate a large amount of short and medium lived helper objects.

Update for the comments: The objects itself are mainly loaded by an EntityFramework context (so the dictionary is not the GC root) and the dictionaries are not resused since used in a context class like so:

internal sealed class TransformationContext : IDisposable
{
   private readonly Dictionary<ClassA,ClassB> dict1 = new ...;
   private readonly Dictionary<ClassC,ClassD> dict2 = new ...;
   private readonly Dictionary<ClassE,ClassF> dict3 = new ...;

   public void Dispose() // class is sealed, classic Dispose-pattern not needed
   {
     dict1.Clear();
     dict2.Clear();
     dict3.Clear();
   }
}

using(var context = new TransformationContext(some, input, values))
  [...]
springy76
  • 3,706
  • 2
  • 24
  • 46
  • related: http://stackoverflow.com/questions/1400532/differences-between-dictionary-clear-and-new-dictionary – Tim Schmelter Sep 28 '15 at 09:00
  • 1
    It is not wrong. Is there any point in keeping them around at all when you can just as easily create a new Dictionary? Do keep in mind that Clear() does not release the storage that was allocated for the dictionary. You only give the GC a chance to destroy the element objects, not the dictionary. That can be good or bad, depends. Bad when you don't use the dictionary for a while and/or the next load has a very different size. – Hans Passant Sep 28 '15 at 09:05
  • @HansPassant just added sample code -- could the `Clear()` have bad influence on GC roots (may they be reassigned at all at any time)? – springy76 Sep 28 '15 at 09:49
  • Finger nails on a black-board, never lie about what Dispose() does. The programmer that uses this class will not keep using the object, since he disposed it, so it is going to be garbage collected. Both the TransformationContext object and the dictionaries will be collected at the same time since you said they are in gen #2. So there's no point whatsoever in calling Clear(). – Hans Passant Sep 28 '15 at 10:01
  • @HansPassant that's the key of the question. Will Clear() in any way help the GC by removing complexiness from the reference graph or is it really worthless at all? And yes it matters if a gen2-collection freezes my app for 3 seconds or for 90 seconds (yes, I have seen the GC acting that bad when there are millions of live objects). – springy76 Sep 28 '15 at 11:11

0 Answers0