San*_*osh 11 c# performance dictionary
我想要一些建议,以最小的内存占用和最大的访问性能来存储和访问.
例如.对于每辆车,我想存储型号和名称.
我有以下一些想法:
选项1:
Dictionary<string, Dictionary<string, string>> values = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("2001", "Jetta S");
list.Add("2002", "Jetta SE");
list.Add("2002", "Jetta LE");
values.Add("VolksWagen", list);
Run Code Online (Sandbox Code Playgroud)
选项2:
Dictionary<string, List<KeyValuePair<string, string>>> values2 = new Dictionary<string, List<KeyValuePair<string, string>>>();
<pre lang="xml">List<KeyValuePair<string, string>> list2 = new List<KeyValuePair<string, string>>();
list2.Add(new KeyValuePair<string, string>("2001", "Jetta S"));
list2.Add(new KeyValuePair<string, string>("2002", "Jetta SE"));
list2.Add(new KeyValuePair<string, string>("2002", "Jetta LE"));
values2.Add("VolksWagen", list2);
Run Code Online (Sandbox Code Playgroud)
选项3:
Dictionary<string, List<string>> values1 = new Dictionary<string, List<string>>();
List<string> list1 = new List<string>();
list1.Add("2001:Jetta S");
list1.Add("2002:Jetta SE");
list1.Add("2002:Jetta LE");
values1.Add("VolksWagen", list1);
Run Code Online (Sandbox Code Playgroud)
上面会有1500多个字典.
任何有关快速访问但内存占用较少的建议都值得赞赏?
谢谢.
Mar*_*ell 19
SortedList<TKey,TValue>
是一个平面列表(所以在内存占用没有大幅增加),即使用二进制搜索访问-如此O(log(n))
-所以没有那么快,因为Dictionary<TKey,TValue>
在O(1)
-但比一个更好的List<T>
(或其他线性搜索)的O(n)
.
如果您想要最快的访问权限,则需要为哈希表使用额外的内存.
作为附注,SortedList<TKey,TValue>
也允许通过int索引进行高效访问,这对于难以实现SortedDictionary<TKey,TValue>
并且几乎毫无意义Dictionary<TKey,TValue>
.
显然,在您的场景中,您可能需要与嵌套或复合键结合 SortedList<,>
使用 - 但IMO将是获得内存和访问器性能平衡的最佳途径.你可以使用一个专用的复合键,即一个iummutable struct
用组合键成员,覆盖GetHashCode()
和Equals
,实施IEquatable<T>
,并进行排序:实施IComparable
和IComparable<T>
.