Friday, 20 March 2015

c# hashtable vs dictionary

Hashtable and Dictionary both of them are used to maintain the key, value pair only there is some basic difference that makes us to opt, any of this 2 based on the situations.

Differences  between Hashtable and Dictionary.

1.       Declaration of Hashtable and dictionary;
Dictionary:
Dictionary<int, string> dict = new Dictionary<int, string>();

Hashtable :
Hashtable hst = new Hashtable();



2.       Namespace for Hashtable and dictionary;
Dictionary : It is generic type of collection. Its belongs to the
 using System.Collections.Generic;
Collection family.

Hashtable :  it is non generic type of collection so it belongs to:
using System.Collections; collection family.


3.       Boxing and Unboxing
Dictionary :  At the time of declaration itself we defined the type
Dictionary<int, string>
That’s why no need of any type casting; at time of retrieval. It will take only the same data type at time of assignment.
dict.Add(1, "1");

Hashtable :  It can store any type of datatype as there is no declaring.
Hashtable hst = new Hashtable();
You can assign any type of data in hash table like below;
hst.Add("1", "1");
hst.Add(1, "1");

At the time getting the value you need to do the unboxing as

int num = (int)oh;
string str = (string)hst[oh];

4.       Performance
Dictionary is faster than hash table as there is no need to do the boxing and unBoxing.
Please see the below code snippet and result.

static void Main(string[] args)
        {
            Console.WriteLine(" 1) Start : - " + DateTime.Now);
            Dictionary<int, string> dict = new Dictionary<int, string>();
            dict.Add(1, "1");
            for (int i = 0; i <= 1000000; i++)
            {
                dict.Add(i, "value " + i);
            }

            foreach (var o in dict)
            {
                int num = o.Key;
                string str = o.Value;
              
            }

            Console.WriteLine("End : - " + DateTime.Now);

            Console.WriteLine(" 2) Start : - " + DateTime.Now);
            Hashtable hst = new Hashtable();
            hst.Add("1", "1");
            hst.Add(1, "1");
            for (int j = 0; j <= 1000000; j++)
            {
                hst.Add(j, "value " + j);
            }
          
            foreach (var oh in hst.Keys )
            {
                int num = (int)oh;
                string str = (string)hst[oh];
            }
            Console.WriteLine("End : - " + DateTime.Now);
        }


1 comment: