Pranay Rana: Dictionary Object (ContainsKey Vs. TryGetValue)

Saturday, June 18, 2011

Dictionary Object (ContainsKey Vs. TryGetValue)

Here I am going to discuss about two important method of the Dictionary<tkey, tvalue> class to play with the data of the Dictionary.

Dictionary<tkey, tvalue> class allows us to create key , vlaue pair collection. The Dictionary<tkey, tvalue> generic class maps of keys to a set of values. Dictionary consists of a value and its associated key. Value can be retived by using its key is very fast, close to O(1), because the Dictionary>tkey, tvalue< class is implemented as a hash table.
Now to understand what I am going to discuss in this post

I am creating Dictionary object
Dictionary<string, string> dic = new Dictionary<string, string>();
Dictionary Class has method Add which allows to add the key, value pair data in the dictionary object
dic.Add("Pranay",  "Rana");
dic.Add("Hemang", "Vyas");
dic.Add("Krunal", "Mevada");
dic.Add("Hanika",  "Arora");
Now after adding the key,value pair it's need to take out the value out of the dictionary object and use that values because after all dictionary object used to store the values and to get it back.
To take value back from the Dictionary object , it require to make use of key
Type value = dic[key];
But the problem with this is it throws KeyNotFoundException if the key is not exists in dictionary.

ContainsKey 
Dictionary class provide methods ContainsKey which used to check where the key is present or not.
Signature bool ContainsKey(<TKey> key)
So most of the developer use this method to check value and if the value is exits they get the value back.
if (dic.ContainsKey(key))
{
     string result = dic[key];
     Console.WriteLine(result);
}
TryGetValue
But Dictionary object provide one more method TryGetValue which check key is present in dictionary present or not and if present return value by out parameter.
Signature bool TryGetValue(<TKey> key,out <TValue> val)
By using the method code is like
if (dic.TryGetValue(key, out val))
{
   Console.WriteLine(val);
}
By using two method one can avoid throwing the KeyNotFoundException.

But the question is What is the difference between two approach related to ContainsKey and TryGetValue ?
The first diffrence is ContainsKey approach only checks weather key is present or not and than get the value , but the TryGetValue not only check key is present or not but also get the value for that key.
So the TryGetValue make code easy and simple.

The second difference is TryGetValue approach is faster than ContainsKey.
To check out I wrote following code and executed on my machine.
Note : Stopwatch class exists in System.Diagnostics Namespace to get the time require to execute the line of code.
Dictionary<string, string> dic = new Dictionary<string, string>();
      dic.Add("Pranay",  "Rana");
      dic.Add("Hemang", "Vyas");
      dic.Add("Krunal", "Mevada");
      dic.Add("Hanika",  "Arora");

      //First method ContainsKey
      Stopwatch st = new Stopwatch();
      st.Start();
      foreach (string key in dic.Keys)
      {
          if (dic.ContainsKey(key))
          {
             string result = dic[key];
             Console.WriteLine(result);
          }
      }
      st.Stop();
      TimeSpan ts = st.Elapsed;
      Console.WriteLine("RunTime " + ts.Milliseconds);


      //Second method TryGetValue
      string val = string.Empty;
      Stopwatch st1 = new Stopwatch();
      st1.Start();
      foreach (string key in dic.Keys)
      {
          if (dic.TryGetValue(key, out val))
          {
              Console.WriteLine(val);
          }
      }
      st1.Stop();
      ts = st1.Elapsed;
      Console.WriteLine("RunTime " + ts.Milliseconds);

After the test I got following output
As you can see in the image the first one take 4 millisecond to get the values and the later one take 1 millisecond.

Note :
TryGetValue approach is faster than ContainsKey approach but only when you want to check the key in collection and also want to get the value associated with it. If you only want to check the key is present or not use ContainsKey only.

1 comment:

  1. If you want to check the real differce between two paste code in two different file and than test
    like as below

    static void Main(string[] args)
    {
    Dictionary dic = new Dictionary();
    dic.Add("Pranay", "Rana");
    dic.Add("Hemang", "Vyas");
    dic.Add("Krunal", "Mevada");
    dic.Add("Hanika", "Arora");

    Stopwatch st = new Stopwatch();
    st.Start();
    for (int i = 0; i < 20; i++)
    {
    foreach (string key in dic.Keys)
    {
    if (dic.ContainsKey(key))
    {
    string result = dic[key];
    Console.WriteLine(result);
    }
    }
    }
    st.Stop();
    TimeSpan ts = st.Elapsed;
    // Format and display the TimeSpan value.
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
    ts.Hours, ts.Minutes, ts.Seconds,
    ts.Milliseconds / 10);
    Console.WriteLine("contains RunTime " + ts.Milliseconds);


    Console.ReadLine();

    }

    and in second file

    static void Main(string[] args)
    {
    Dictionary dic = new Dictionary();
    dic.Add("Pranay", "Rana");
    dic.Add("Hemang", "Vyas");
    dic.Add("Krunal", "Mevada");
    dic.Add("Hanika", "Arora");


    string val = string.Empty;
    Stopwatch st1 = new Stopwatch();
    st1.Start();
    for (int i = 0; i < 20; i++)
    {
    foreach (string key in dic.Keys)
    {
    if (dic.TryGetValue(key, out val))
    {
    Console.WriteLine(val);
    }
    }
    }
    st1.Stop();
    TimeSpan ts = st1.Elapsed;
    Console.WriteLine("trygetvalue RunTime " + ts.Milliseconds);
    Console.ReadLine();

    }

    ReplyDelete