What is the best data structure in .Net with high performance lookup, like a binary tree implementation, but to store only the keys (string keys) ?
We need only to check if a certain key is present in the collection. Like:
Dictonary<string, object> myKeys;
myKeys.Add("key1", null);
myKeys.Add("key2", null);
// Dozens or hundreds keys
Assert.IsTrue(myKeys.Contains("key1"));
Looking at complexity analysis, Hashtables seem to be the most efficient for lookups.
A dictionary is 6.6 times faster than a list when we lookup in 100 items.
A heap will only let you search quickly for the minimum element (find it in O(1) time, remove it in O(log n) time). If you design it the other way, it will let you find the maximum, but you don't get both. To search for arbitrary elements quickly (in O(log n) time), you'll want the binary search tree.
The reason is dictionaries are very fast, implemented using a technique called hashing, which allows us to access a value very quickly. By contrast, the list of tuples implementation is slow. If we wanted to find a value associated with a key, we would have to iterate over every tuple, checking the 0th element.
A HashSet
(in System.Collections.Generic
):
HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operation are O(1).
e.g.
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
// Populate numbers with just even numbers.
evenNumbers.Add(i * 2);
// Populate oddNumbers with just odd numbers.
oddNumbers.Add((i * 2) + 1);
}
if (evenNumbers.Contains(2))
{
Console.WriteLine("2 is even.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With