Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Collection for Fast String Lookup

I need a list of strings and a way to quickly determine if a string is contained within that list.

To enhance lookup speed, I considered SortedList and Dictionary; however, both work with KeyValuePairs when all I need is a single string.

I know I could use a KeyValuePair and simply ignore the Value portion. But I do prefer to be efficient and am just wondering if there is a collection better suited to my requirements.

like image 998
Jonathan Wood Avatar asked Apr 03 '11 17:04

Jonathan Wood


2 Answers

If you're on .NET 3.5 or higher, use HashSet<String>.

Failing that, a Dictionary<string, byte> (or whatever type you want for the TValue type parameter) would be faster than a SortedList if you have a lot of entries - the latter will use a binary search, so it'll be O(log n) lookup, instead of O(1).

like image 163
Jon Skeet Avatar answered Oct 06 '22 13:10

Jon Skeet


If you just want to know if a string is in the set use HashSet<string>

like image 23
BrokenGlass Avatar answered Oct 06 '22 12:10

BrokenGlass