C# Dictionary的遍歷理解

C# Dictionary容器類的理解


本文章由cartzhang編寫,轉載請註明出處。 全部權利保留。
文章連接:http://blog.csdn.net/cartzhang/article/details/52490249
做者:cartzhang
html

1、Dictionary容器類的內部實現

在C#中,Dictionary 是一個鍵值對應。每一個Key在字典內都是惟一的。也就是說全部鍵值都是惟一的一對。算法

他們都須要繼承IDictionary<K,V>()類,固然IDictionary<K,V>()繼承與Collection<KeyValuePair<K,V>>,
而它ICollection<KeyValuePair<K,V>>()繼承與IEnumerable類。

sss

2、Dictionary的迭代

Dictionary < TKey, TValue > Class 的迭代方式有兩種:
1. foreach
sql

foreach (KeyValuePair item in myDictionary)
{
    MessageBox.Show(item.Key + " " + item.Value);
}


2.for 循環
markdown

for (int count = 0; count < myDictionary.Count; count++)
{
    var element = myDictionary.ElementAt(count);
    var Key = element.Key;
    var Value = element.Value;
    MessageBox.Show(Key + " " + Value);
}

3、相關容器類

1.Class Dictionary<K,V>     
  基於hash table.
2.SortedDictionary<K,V>  
  基於二叉樹搜索
3.SortedList<K,V>
  基於排序的Collection。

他們之間的算法複雜度比較:dom

做爲colletion容器類,Dictionary仍是表現特別良好的。
這裏寫圖片描述
svg

4、Dictionary 與List比較

執行效率對比:
與List相對比:Dictionary的O(n)是固定的。而list隨長度增長。
這裏寫圖片描述
oop

5、Dictionary的迭代方法對比

Foreach的迭代方法有三種:優化

Dictionary<double, double>.ValueCollection valueColl = randomDictionaryOfDoubles.Values;

一個是KeyValuePairspa

foreach (KeyValuePair<double, double> kvp in randomDictionaryOfDoubles)
{
    total += (kvp.Value);
}

一個是ValueCollection.net

foreach (double d in valueColl)
{
    total += d;
}

一個是keyCollection

foreach (double d in keyColl)
{
    total += d;
}

這裏寫圖片描述

這個很明顯的就是效率問題:經過KeyCollection遍歷效率高於ValueCollection的遍歷效率,而ValueCollection的遍歷效率高於key-ValuePairs。
簡而言之:keyCollection > ValueCollection>key-valuePairs.
各位能夠斟酌使用啊。

6、關於GC

由於在項目中,有同窗使用Dictionary過程當中,Foreach的過程當中,
有GC。到底在遍歷過程當中會不會產生不少GC呢?仍是咱們的使用方法不對呢?因此讓我幫忙看下。
正好看下GC的流程。
這裏寫圖片描述

最好的問題,我的以爲應該是Unity的.Net 對應版本比較低,形成優化比較很差的問題。
這個在接下來,我會簡單比較下。

先回去睡覺了。就這樣。


參考:
1. http://csharp.net-informations.com/collection/dictionary.htm
2. http://net-informations.com/q/faq/dictionary.html
3. http://people.cs.aau.dk/~normark/oop-csharp/html/notes/collections_themes-dictionary-sect.html
4. http://people.cs.aau.dk/~normark/oop-csharp/html/notes/collections_themes-list-sect.html#collections_collection-overview-1_svg-image_i1
5. http://alexpinsker.blogspot.com/2010/02/c-fastest-way-to-iterate-over.html
6. http://www.cnblogs.com/jeffwongishandsome/p/talk-about-GC-and-how-to-use-GC-better.html

——————-THE———–END————————–
如有問題,請隨時聯繫!!!
很是感謝!!!
夢想有個車!!
人想法仍是要有的!!!
這裏寫圖片描述

相關文章
相關標籤/搜索