Performance Bench mark: Dictionary VS Concurrent Dictionary in Single Thread

  1. class Program  
  2.   
  3. {  
  4.   
  5. static void Main(string[] args)  
  6.   
  7. {  
  8.   
  9. var dict = new Dictionary<intint>();  
  10.   
  11. var dict1 = new ConcurrentDictionary<intint>();  
  12.   
  13. Stopwatch stopwatch = new Stopwatch();  
  14.   
  15. stopwatch.Start();  
  16.   
  17. PopulateDictionary(dict, 1000000);  
  18.   
  19. stopwatch.Stop();  
  20.   
  21. Console.WriteLine("Dictionary Write: " + stopwatch.ElapsedMilliseconds);  
  22.   
  23. stopwatch.Restart();  
  24.   
  25. int total = GetTotal(dict);  
  26.   
  27. stopwatch.Stop();  
  28.   
  29. Console.WriteLine("Dictionary Read: " + stopwatch.ElapsedMilliseconds);  
  30.   
  31. stopwatch.Restart();  
  32.   
  33. PopulateDictionary(dict1, 1000000);  
  34.   
  35. stopwatch.Stop();  
  36.   
  37. Console.WriteLine("ConcurrentDictionary Write: " + stopwatch.ElapsedMilliseconds);  
  38.   
  39. stopwatch.Restart();  
  40.   
  41. total = GetTotal(dict1);  
  42.   
  43. stopwatch.Stop();  
  44.   
  45. Console.WriteLine("ConcurrentDictionary Read: " + stopwatch.ElapsedMilliseconds);  
  46.   
  47. Console.ReadKey();  
  48.   
  49. }  
  50.   
  51. static void PopulateDictionary(IDictionary<intint> dict, int size)  
  52.   
  53. {  
  54.   
  55. for (int i = 0; i < size; i++)  
  56.   
  57. {  
  58.   
  59. dict.Add(i, i);  
  60.   
  61. }  
  62.   
  63. }  
  64.   
  65. static int GetTotal(IDictionary<intint> dict)  
  66.   
  67. {  
  68.   
  69. int total = 0;  
  70.   
  71. foreach (var item in dict)  
  72.   
  73. {  
  74.   
  75. total += dict[item.Value];  
  76.   
  77. }  
  78.   
  79. return total;  
  80.   
  81. }  
  82.   
  83. }  

Conclusion: In single thread environment concurrent dictionary is costlier than dictionary.