Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

c# - Differences between Dictionary.Clear and new Dictionary()

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...