什么时候应该使用sorteddictionary而不是Dictionary [英] when should I use a sorteddictionary instead of a dictionary

查看:90
本文介绍了什么时候应该使用sorteddictionary而不是Dictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我在前几篇文章中所写的那样,我对c#领域还是一个陌生的人,因此我写了一个小的基准来比较Dictionary,Hashtable,SortedList和SortedDictionary.该测试运行8000次迭代,并包含50到100000个元素.我测试了添加新元素,搜索元素以及遍历所有元素的过程,这些过程都是随机的.结果与我预期的一样,只是SortedDictionary的结果令我感到困惑……所有结果都太慢了.我是否也错过了有关排序字典的概念.我已经问过google了,但是我发现所有其他人都得出了相同的测试结果.根据其实施的测试略有不同.再一次我的问题是:为什么SortedDicrionary这么慢?

As I wrote in some of my last posts I am still quite new to the c# world so it comes that I wrote small benchmark to compare Dictionary, Hashtable, SortedList and SortedDictionary against each other. The test runs with 8000 iterations and from 50 to 100000 elements. I tested adding of new elements, search for elements and looping through some elements all random. The results was as I expected them to be except the result of the SortedDictionary which was much confusing for me... It was just slow in all results. So did I missing sometging about the concept of a sorted dictionary. I already asked google but All that I found out was that others had come to the same test result. Slightly different based on their implementation of the test. Again my question: why is the SortedDicrionary so much slower than all the others?

推荐答案

SortedDictionary被实现为二进制搜索树.因此,访问元素是O(lg(n)).字典是一个哈希表,访问复杂度为O(1).

A SortedDictionary is implemented as a binary search tree. Therefore, accessing an element is O(lg(n)). A Dictionary is a hash table, and has a complexity of O(1) for access.

当您需要对数据进行排序(字典没有定义的顺序)时,SortedDictionary非常有用.字典适用于大多数情况.

A SortedDictionary is quite useful when you need the data to be sorted (a Dictionary has no defined order). Dictionary is appropriate for most cases.

这篇关于什么时候应该使用sorteddictionary而不是Dictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆