c# .net Compact Framework 3.5 中最快的字典查找

发布于 2024-10-31 16:02:44 字数 643 浏览 1 评论 0原文

我正在寻找查找列表、集合、字典是否包含特定关键字(字符串)的最快方法。我不需要在里面存储任何数据,我只想知道我的关键字是否在列表中。

我考虑了一些可能性,例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

鸠魁 2024-11-07 16:02:45

在标准集合类型中,Dictionary 将是最快的,因为我认为紧凑框架中没有 HashSet。另外两个进行顺序搜索。

Of the standard collection types, Dictionary will be the fastest, since I don't think you have HashSet<T> in the compact framework. The other two do a sequential search.

单身狗的梦 2024-11-07 16:02:45

一般来说,字典查找是此类问题的常用解决方案,只要您的键是良好的哈希值,并且在字典的查找表中分布均匀即可。

但是,在某些情况下,列表查找似乎运行得更快,具体取决于数据的排序方式以及您到底要查找的内容。

最好的判断方法是运行每个案例的配置文件,看看哪个表现更好。

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.

墟烟 2024-11-07 16:02:45

我同意安迪的观点。您还可以查看 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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文