ConcurrentDictionary<> performance at a single thread misunderstanding?

.net-4.0, c#, concurrentdictionary, task-parallel-library

Solution

The most likely reason that `ConcurrentDictionary` simply has more overhead than `Dictionary` for the same operation. This is demonstrably true if you dig into the sources

- It uses a lock for the indexer

- It uses volatile writes

- It has to do atomic writes of values which are not guaranteed to be atomic in .Net

- It has extra branches in the core add routine (whether to take a lock, do atomic write)

All of these costs are incurred irrespective of the number of threads that it's being used on. These costs may be individually small but aren't free and do add up over time

Problem

Related brief info: AFAIK , The concurrent stack, queue, and bag classes are implemented internally with linked lists. And I know that there is much less contention because each thread is responsible for its own linked list. Any way , my question is about the `ConcurrentDictionary<,>` But I was testing this code :(single thread) ``` Stopwatch sw = new Stopwatch(); sw.Start(); var d = new ConcurrentDictionary < int, int > (); for(int i = 0; i < 1000000; i++) d[i] = 123; for(int i = 1000000; i < 2000000; i++) d[i] = 123; for(int i = 2000000; i < 3000000; i++) d[i] = 123; Console.WriteLine("baseline = " + sw.Elapsed); sw.Restart(); var d2 = new Dictionary < int, int > (); for(int i = 0; i < 1000000; i++) lock (d2) d2[i] = 123; for(int i = 1000000; i < 2000000; i++) lock (d2) d2[i] = 123; for(int i = 2000000; i < 3000000; i++) lock (d2) d2[i] = 123; Console.WriteLine("baseline = " + sw.Elapsed); sw.Stop(); ``` Result : (tested many times, same values (+/-)). ``` baseline = 00:00:01.2604656 baseline = 00:00:00.3229741 ``` Question : What makes `ConcurrentDictionary<,>` much slower in a single threaded environment ? My first instinct is that `lock(){}` will be always slower. but apparently it is not.

Original source

Related problems