c# .net Compact Framework 3.5 中最快的字典查找
我正在寻找查找列表、集合、字典是否包含特定关键字(字符串)的最快方法。我不需要在里面存储任何数据,我只想知道我的关键字是否在列表中。
我考虑了一些可能性,例如:
Dictionary<string, bool> myDictionary = new Dictionary<string, bool>();
if (myDictionary.ContainsKey(valueToSearch))
{
// do something
}
但我不需要一个值。
string[] myArray = {"key1", "key2", "key3"}
if (Array.IndexOf(myArray, valueToSearch) != -1)
{
// do something
}
然后我发现:
List<string> list = new List<string>();
if (list.Contains(valueToSearch))
{
// do something
}
查找会经常发生并且必须非常快。 知道检查某个值是否等于给定键列表之一的最快方法是什么吗?
I'm looking for the fastest way to lookup if List, Set, Dictionary contains a specific Keyword (string). I don't need to store any data inside I just want to know if my Keyword is in the List.
I thought about some possibilities like:
Dictionary<string, bool> myDictionary = new Dictionary<string, bool>();
if (myDictionary.ContainsKey(valueToSearch))
{
// do something
}
but I don't need a value.
string[] myArray = {"key1", "key2", "key3"}
if (Array.IndexOf(myArray, valueToSearch) != -1)
{
// do something
}
Then I found:
List<string> list = new List<string>();
if (list.Contains(valueToSearch))
{
// do something
}
The lookup will happen very often and has to be very fast.
Any idea what's the fastest way to check if a value equals one of a given list of keys?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在标准集合类型中,
Dictionary
将是最快的,因为我认为紧凑框架中没有HashSet
。另外两个进行顺序搜索。Of the standard collection types,
Dictionary
will be the fastest, since I don't think you haveHashSet<T>
in the compact framework. The other two do a sequential search.一般来说,字典查找是此类问题的常用解决方案,只要您的键是良好的哈希值,并且在字典的查找表中分布均匀即可。
但是,在某些情况下,列表查找似乎运行得更快,具体取决于数据的排序方式以及您到底要查找的内容。
最好的判断方法是运行每个案例的配置文件,看看哪个表现更好。
In general, a Dictionary lookup is the usual solution to a problem like this, as long as your keys are good hash values that get a somewhat even distribution in the dictionary's lookup table.
However, there may be certain cases where a list lookup appears to run faster, depending on how the data is sorted and what exactly you are looking up.
The best way to tell is to run a profile of each case, and see which performs better.
我同意安迪的观点。您还可以查看 SortedList 它本质上是一个按其键排序的字典。如果已经排序,应该可以使搜索更快......
I agree with Andy. You could also look at SortedList It's essentially a Dictionary that's sorted by its keys. Should make searching quicker if it's already sorted...