简体   繁体   中英

Fastest Dictionary lookup in c# .net Compact Framework 3.5

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?

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.

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM