Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashTable or Dictionary lookup time

Is the Lookup Time for a HashTable or Dictionary Always O(1) as long as it has a Unique Hash Code?

If a HashTable has 100 Million Rows would it take the same amount of time to look up as something that has 1 Row?

like image 739
jquery auth Avatar asked Oct 21 '10 10:10

jquery auth


People also ask

Is a hash table faster than a dictionary?

Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.

Which is faster dictionary or list for lookup?

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

Why does searching a lookup table take O 1 time?

You're missing the most important "feature" of a hash table, which is that the hash code of the key is used to map the key to a position in the array of buckets. So, given a key, finding the index in the array of buckets takes a constant time (given the hash code calculation is based only on the the value of the key).

Should I use Hashtable or dictionary?

In Hashtable, you can store key/value pairs of the same type or of the different type. In Dictionary, you can store key/value pairs of same type. In Hashtable, there is no need to specify the type of the key and value. In Dictionary, you must specify the type of key and value.


2 Answers

No. It is technically possible but it would be extremely rare to get the exact same amount of overhead. A hash table is organized into buckets. Dictionary<> (and Hashtable) calculate a bucket number for the object with an expression like this:

int bucket = key.GetHashCode() % totalNumberOfBuckets;

So two objects with a different hash code can end of in the same bucket. A bucket is a List<>, the indexer next searches that list for the key which is O(n) where n is the number of items in the bucket.

Dictionary<> dynamically increases the value of totalNumberOfBuckets to keep the bucket search efficient. When you pump a hundred million items in the dictionary, there will be thousands of buckets. The odds that the bucket is empty when you add an item will be quite small. But if it is by chance then, yes, it will take just as long to retrieve the item.

The amount of overhead increases very slowly as the number of items grows. This is called amortized O(1).

like image 69
Hans Passant Avatar answered Sep 21 '22 01:09

Hans Passant


Might be helpful : .NET HashTable Vs Dictionary - Can the Dictionary be as fast?

like image 36
PRR Avatar answered Sep 21 '22 01:09

PRR