2011-05-20 100 views
18

如果我想將物品放入System.Collections.Generic.Dictionary,我可以選擇Add或設置ItemSystem.Collections.Generic.Dictionary`Add` vs set`Item`

我知道如果我們做Add它檢查密鑰是否已經存在,如果不存在,則會引發異常。

因此,當添加一噸物品時,我應該更喜歡設置Item而不是Add,因爲Add會進行不必要的檢查,這可能實際上會減慢速度?

回答

35

這裏是指設置項目會發生什麼:

public void set_Item(TKey key, TValue value) 
{ 
    this.Insert(key, value, false); 
} 

這裏是當你添加的項目會發生什麼:

public void Add(TKey key, TValue value) 
{ 
    this.Insert(key, value, true); 
} 

最後一個參數最後布爾add參數只是影響該行:

if (add) 
{ 
    ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); 
} 

所以如果你想在你添加一個重複項目時出現異常, d使用Add。如果你想覆蓋退出的項目,你需要設置項目。

+1

一個偉大的沒有廢話的答案。 – 2011-05-20 04:04:55

+1

你是怎麼做到的?我無法找到「代碼背後」 – Pacerier 2011-05-20 04:29:33

+1

@Prier,做一個谷歌搜索**反射器** – Stormenet 2011-05-27 09:35:08

3

這一切取決於您是要處理重複密鑰還是覆蓋任何可能存在的項目。要檢查您可以使用的重複項:

例如:

var dict = new Dictionary<int, string>(); 

Console.WriteLine(dict.ContainsKey(1)); // false 
dict[1] = "hi"; 
dict[1] = "hello"; // "hi" is overwritten 

// true: hello 
Console.WriteLine("{0}: {1}", dict.ContainsKey(1), dict[1]); 

// TryGetValue if checking by key and interested in the value 
string result; 
if (dict.TryGetValue(1, out result)) 
{ 
    Console.WriteLine("Key 1 exists: " + result); 
} 
else 
{ 
    Console.WriteLine("Key 1 not found"); 
} 
+0

'包含'會更好的檢查重複? – 2011-05-20 04:04:39

+0

@Alex'Dictionary'類提供的'ContainsKey'或'ContainsValue'方法將是一個不錯的選擇。你是指那些還是'Enumerable.Contains'?如果是後者,則需要首先投射'Keys'集合,例如'dict.Keys.Cast ().Contains(1)',根據提供的可用方法,這是不值得的。 – 2011-05-20 04:11:44

+0

對不起,我的意思是ContainsKey。 – 2011-05-20 04:22:22

2

拋出異常低廉,其處理他們是昂貴的。 try/catch塊的try部分像正常一樣運行。當一個catch塊被執行時,它必須展開堆棧以填充堆棧跟蹤(等等)。這是使異常昂貴的原因。這是爲了避免捕捉異常的原因,如果你你有辦法通過使用諸如Dictionary<T>.ContainsKey

這是極不可能的,你永遠不會通知,要求添加和設置項目之間的性能差異這樣做。因此,請使用最適合這種情況的方法。

更新: 除非速度慢,否則不要優化您的代碼。

相關問題