C# Dictionary.Clear 和 new Dictionary() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1400532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 16:06:09  来源:igfitidea点击:

Differences between Dictionary.Clear and new Dictionary()

c#.netdictionary

提问by Newbie

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

C#Dictionary.Clearnew Dictionary()C#之间的主要区别是什么?在哪些情况下推荐使用哪一种?

采纳答案by Reed Copsey

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

Dictionary.Clear()将删除KeyValue字典中的所有对。这样做new 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.

当且仅当旧版本的字典没有被另一个引用作为根时,创建一个新字典将使整个字典及其内容(不在其他地方根)可供 GC 清理。

Dictionary.Clear()will make the KeyValuepairs available for cleanup.

Dictionary.Clear()将使这些KeyValue对可用于清理。

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

回答by Chris Marisic

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

Dictionary.clear 将驱逐字典中的所有项目。new Dictionary 在内存中创建一个新的字典对象,同时孤立您以前的 Dictionary 以便垃圾收集器稍后清理。

回答by RSolberg

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

Dictionary.Clear()
这将删除字典中的所有键/值对。垃圾收集器将在下一个垃圾收集周期清除这些项目的内存。 MSDN

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

new Dictionary()
在内存中创建一个新的 Dictionary 对象,并放弃原来的对象。内存将在下一个垃圾收集周期中被清除。

回答by Ant

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

我想关键区别在于,如果您调用Dictionary.Clear(),则对该词典的所有引用都将被清除。如果您使用new Dictionary(),那么您当时正在处理的引用将被清除(在某种意义上),但您引用的所有其他地方都不会被清除,因为它们仍将引用旧字典。

Hopefully 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 called d1.Clear()instead, then d1 and d2 would have remained in sync, and the subsequent adds would have added to both. The WriteLine calls would both have output '3' instead.

如果我d1.Clear()改为调用,则 d1 和 d2 将保持同步,随后的添加将添加到两者中。WriteLine 调用都会改为输出“3”。

回答by gshauger

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

如果您对该词典有多个引用并且清除它,则会影响所有引用,就像创建新词典一样,您只会影响一个新引用。我想这取决于您所针对的影响范围。显然,调用“new”会给你一个“清除”的字典,但你可能会丢失其他有用的状态信息。

回答by Brian Gideon

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

Dictionary.Clear将删除(但不处理)实例中的所有项目,而new Dictionary()将创建一个刚好为空的全新实例。两者之间可能有一些微妙的含义。考虑以下示例。

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 the first example all of the contents from the original collection will be printed. That is because the enumerator was created from the reference variable before it was reassigned to a new instance.

在第一个示例中,将打印原始集合中的所有内容。这是因为枚举器是在将引用变量重新分配给新实例之前从引用变量创建的。

In the second example the collection is cleared during an enumeration which will result in an InvalidOperationExceptionbecause the collection was modified.

在第二个示例中,在枚举期间清除了集合,这将导致 ,InvalidOperationException因为集合已被修改。

回答by womp

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

正如已经广泛覆盖的那样,效果基本相同。 Clear()并且new都将为您提供一个新的字典,基本上放弃对其中对象的引用,如果它们无根,则将它们释放出来以供收集。

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

从技术上讲,如果您要将字典重新填充到与以前相同的大小,这.Clear()将具有优势new。这是因为它已经在内部调整大小以保存您之前拥有的对象数量。创建一个新的 Dictionary 将有一个具有默认大小的新内部哈希表,并且在您向其中添加项目时必须重新扩展它。

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

我还建议他们传达一个完全不同的意图,.Clear()当您处理与以前相同的上下文时,您应该在代码中使用。创建一个新的 Dictionary 意味着您将开始处理一些与旧 Dictionary 不同的新逻辑,而 usingClear()表示是的,您真的只想重置您迄今为止所做的一切。

回答by womp

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.

我相信提供 .Clear() 是为了如果您的 Dictionary 公开为只读属性,您将能够删除所有项目。但是,如果它没有以这种方式公开,并且您拥有完全的控制权,那么实例化一个新的 Dictionary 可能会更容易。两者之间也可能存在轻微的性能差异。