本文章由cartzhang编写,转载请注明出处。 全部权利保留。
文章连接:http://blog.csdn.net/cartzhang/article/details/52490249
做者:cartzhanghtml
在C#中,Dictionary 是一个键值对应。每一个Key在字典内都是惟一的。也就是说全部键值都是惟一的一对。算法
他们都须要继承IDictionary<K,V>()类,固然IDictionary<K,V>()继承与Collection<KeyValuePair<K,V>>,
而它ICollection<KeyValuePair<K,V>>()继承与IEnumerable类。
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);
}
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
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.
各位能够斟酌使用啊。
由于在项目中,有同窗使用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————————–
如有问题,请随时联系!!!
很是感谢!!!
梦想有个车!!
人想法仍是要有的!!!