class Program
{
static void Main(string[] args)
{
var dict = new Dictionary<int, int>();
var dict1 = new ConcurrentDictionary<int, int>();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
PopulateDictionary(dict, 1000000);
stopwatch.Stop();
Console.WriteLine("Dictionary Write: " + stopwatch.ElapsedMilliseconds);
stopwatch.Restart();
int total = GetTotal(dict);
stopwatch.Stop();
Console.WriteLine("Dictionary Read: " + stopwatch.ElapsedMilliseconds);
stopwatch.Restart();
PopulateDictionary(dict1, 1000000);
stopwatch.Stop();
Console.WriteLine("ConcurrentDictionary Write: " + stopwatch.ElapsedMilliseconds);
stopwatch.Restart();
total = GetTotal(dict1);
stopwatch.Stop();
Console.WriteLine("ConcurrentDictionary Read: " + stopwatch.ElapsedMilliseconds);
Console.ReadKey();
}
static void PopulateDictionary(IDictionary<int, int> dict, int size)
{
for (int i = 0; i < size; i++)
{
dict.Add(i, i);
}
}
static int GetTotal(IDictionary<int, int> dict)
{
int total = 0;
foreach (var item in dict)
{
total += dict[item.Value];
}
return total;
}
}
Conclusion: In single thread environment concurrent dictionary is costlier than dictionary.
