Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best lookup data structure to store only the keys (Dictionary without value)

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")); 
like image 731
Luciano Avatar asked Dec 09 '13 23:12

Luciano


People also ask

Which data structure is best for lookup?

Looking at complexity analysis, Hashtables seem to be the most efficient for lookups.

Which is faster dictionary or list for lookup?

A dictionary is 6.6 times faster than a list when we lookup in 100 items.

In which data structure lookup is fast?

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.

Why is dictionary fast?

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.


1 Answers

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.");
    }
  • Introducing HashSet
  • HashSet vs. List performance
like image 147
Mitch Wheat Avatar answered Oct 04 '22 14:10

Mitch Wheat