[ACCEPTED]-Differences between Dictionary.Clear and new Dictionary()-dictionary

Accepted answer
Score: 39

Dictionary.Clear() will remove all of the KeyValue pairs within the 11 dictionary. Doing new Dictionary() will create a new instance 10 of the dictionary.

If, and only if, the old 9 version of the dictionary is not rooted 8 by another reference, creating a new dictionary 7 will make the entire dictionary, and it's 6 contents (which are not rooted elsewhere) available 5 for cleanup by the GC.

Dictionary.Clear() will make the KeyValue pairs 4 available for cleanup.

In practice, both 3 options will tend to have very similar effects. The 2 difference will be what happens when this 1 is used within a method:

void NewDictionary(Dictionary<string,int> dict)
{
   dict = new Dictionary<string,int>(); // Just changes the local reference
}

void  ClearDictionary(Dictionary<string,int> dict)
{
   dict.Clear();
}

// When you use this...
Dictionary<string,int> myDictionary = ...; // Set up and fill dictionary

NewDictionary(myDictionary);
// myDictionary is unchanged here, since we made a new copy, but didn't change the original instance

ClearDictionary(myDictionary);
// myDictionary is now empty
Score: 23

As has been extensively covered, the effects 23 are essentially the same. Clear() and new would both 22 give you a fresh Dictionary, essentially 21 abandoning the references to the objects 20 inside of it, freeing them to be collected 19 if they became unrooted.

Technically, .Clear() would 18 have an advantage over new if you were about 17 to repopulate the dictionary to the same 16 size as it was before. This is because 15 it would have been already resized internally 14 to hold the number of objects that you had 13 in it before. Creating a new Dictionary 12 would have a new internal hashtable with 11 the default size, and it would have to be 10 re-expanded as you added items to it.

I would 9 also suggest that they communicate a completely 8 different intent, and you should use .Clear() in 7 your code when you're dealing with the same 6 context as before. Creating a new Dictionary 5 implies that you are about to embark on 4 some new logic dealing with something different 3 than the old Dictionary, while using Clear() indicates 2 that yes, you really wanted to just reset 1 everything you've done so far with it.

Score: 14

Dictionary.Clear()
This will remove all key/value pairs within 7 the Dictionary. The Garbage Collector 6 will clear the memory for these items during 5 the next Garbage Collection Cycle. MSDN

new Dictionary()
Creates 4 a new Dictionary object in memory and abandons 3 the original object. The memory would be 2 cleared during the next Garbage Collection 1 Cycle.

Score: 6

I suppose the key difference is that if 11 you call Dictionary.Clear(), all references to that dictionary 10 will be cleared. If you use new Dictionary(), then the reference 9 you are dealing with at the time will be 8 cleared (in a sense), but all other places 7 you have references won't be since they 6 will still be referring to the old dictionary.

Hopefully 5 this code illustrates it simply:

public void Method()
{
    Dictionary<int, int> d1 = new Dictionary();

    d1.Add(1,1);
    d1.Add(2,3);

    Dictionary<int, int> d2 = d1;

    //this line only 'clears' d1
    d1 = new Dictionary();

    d1.Add(1,1);
    d1.Add(3,5);
    d2.Add(2,2);

    //writes '2' followed by '1'
    Console.WriteLine(d1.Count);
    Console.WriteLine(d2.Count);
}

If I had 4 called d1.Clear() instead, then d1 and d2 would have 3 remained in sync, and the subsequent adds 2 would have added to both. The WriteLine 1 calls would both have output '3' instead.

Score: 5

Dictionary.Clear will remove (but not dispose) all items 12 in the instance whereas new Dictionary() will create a brand 11 new instance which just happens to be empty. There 10 may be some subtle implications between 9 the two. Consider the following examples.

void Example1()
{
  var collection = new Dictionary<string, string>();
  collection.Add("key1", "value1");
  collection.Add("key2", "value2");
  foreach (var kvp in collection)
  {
    collection = new Dictionary<string, string>();
    Console.WriteLine(kvp);
  }
}

void Example2()
{
  var collection = new Dictionary<string, string>();
  collection.Add("key1", "value1");
  collection.Add("key2", "value2");
  foreach (var kvp in collection)
  {
    collection.Clear();
    Console.WriteLine(kvp);
  }
}

In 8 the first example all of the contents from 7 the original collection will be printed. That 6 is because the enumerator was created from 5 the reference variable before it was reassigned 4 to a new instance.

In the second example 3 the collection is cleared during an enumeration 2 which will result in an InvalidOperationException because the collection 1 was modified.

Score: 3

I believe that .Clear() was provided so 8 that if your Dictionary is exposed as a 7 read-only property you would be able to 6 remove all of the items. However, if it's 5 not exposed that way, and you have complete 4 control then it might be easier to just 3 instantiate a new Dictionary. There might 2 be a slight performance difference between 1 the two, also.

Score: 1

If you have several references to that dictionary 7 and you clear it you will affect them all 6 where as if you create a new dictionary 5 you will only affect the one new reference. I 4 guess it depends on the scope of the impact 3 that you're aiming for. Obviously a call 2 to "new" will give you a "cleared" dictionary 1 but you might lose other useful state information.

Score: 0

Dictionary.clear will evict all of the items 4 in your dictionary. new Dictionary creates 3 a new dictionary object in memory while 2 orphaning your previous Dictionary for the 1 garbage collector to clean up later.

More Related questions