Differences between Dictionary.Clear and new Dictionary()

后端 未结 8 831
情书的邮戳
情书的邮戳 2020-12-15 03:33

What are the key differences between Dictionary.Clear and new Dictionary() in C#? Which one is recommended for which cases?

相关标签:
8条回答
  • 2020-12-15 04:22

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

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

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

    In practice, both options will tend to have very similar effects. The difference will be what happens when this 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
    
    0 讨论(0)
  • 2020-12-15 04:24

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

    0 讨论(0)
提交回复
热议问题