Tuesday, 11 March 2014

Hashtable vs. Dictionary

Hashtable optimizes lookups. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type.
using System.Collections;

class Program
    static Hashtable GetHashtable()
        // Create and return new Hashtable.
        Hashtable hashtable = new Hashtable();

        hashtable.Add("Area", 1000);
        hashtable.Add("Perimeter", 55);
        hashtable.Add("Mortgage", 540);

        return hashtable;

    public  static void Main()
        Hashtable hashtable = GetHashtable();

        // See if the Hashtable contains this key.

        // Test the Contains method. It works the same way.

        // Get value of Area with indexer.
        int value = (int)hashtable["Area"];

        // Write the value of Area.

A dictionary is used where fast lookups are critical. The Dictionary type provides fast lookups with keys to get values. With it we use keys and values of any type, including ints and strings. Dictionary requires a special syntax form.
Dictionary is used when we have many different elements. We specify its key type and its value type. It provides good performance.
class Dict
    static void Main()
           // Example Dictionary again
           Dictionary<string, int> d = new Dictionary<string, int>()
                {"Lion", 2},  {"dog", 1}

           // Loop over pairs with foreach
           foreach (KeyValuePair<string, int> pair in d)
               Console.WriteLine ("{0}, {1}", pair.Key,  pair.Value);

           foreach (var pair in d)
               Console.WriteLine("{0}, {1}", pair.Key, pair.Value);


Differences between Hashtable and Dictionary
1)    It returns error if we try to find a key which does not exist.
2)    It is faster than a Hashtable because there is no boxing and unboxing.
3)    Only public static members are thread safe.
4)    Dictionary is a generic type which means we can use it with any data type.
1)    It returns null if we try to find a key which does not exist.
2)    It is slower than dictionary because it requires boxing and unboxing.
3)    All the members in a Hashtable are thread safe.
4)      Hashtable is not a generic type.

No comments:

Post a Comment