C#: Dictionary Vs ConcurrentDictionary
In this article we are going to benchmark a C# Dictionary Vs ConcurrentDictionary while adding/updating key-value pairs.
This test came about while I was upgrading multiple code blocks from using C# Dictionary objects to ConcurrentDictionary objects. While doing so, I noticed that the application seemed to run slower despite now being multi-threaded.
I couldn’t tell if my eyes were fooling me, or something else was going on, so decided to write some test code to see how much, if at all, changing over to using ConcurrentDictionary objects affected performance.
The code is written in Visual Studio 2015 targeting .Net Framework version 4.5 x64. The source code is available at the end of this blog so you can benchmark it on your own system.
Notes about the code:
- The “DoStuff1()” method is just a bunch of mathematical calculations to replicate heavy handed calculations the real code was doing. I added this in my test code to see if it affected the overall results even though in the test code it returns nothing – I liked it better than just doing a Thread.Sleep.
- For Dictionary objects, I used the ContainsKey and Add methods with array notation d[k] = v for updating along with lock for thread-safety when running in Parallel.For loops
- For ConcurrentDictionary objects, I used the inbuilt AddOrUpdate method.
- I don’t care that the dictionary objects may be used elsewhere in the code if this is a complicated system. We’re just testing the “raw” add/update speeds.
The Benchmarks!
Let’s see what happened on my machine.
All times are indicated in seconds.milliseconds format.
Lower numbers indicate faster performance. Winning times marked in green.
Serial |
Do Stuff? |
1,000 |
100,000 |
10,000,000 |
Dictionary<int,string> |
N |
00.0000687 |
00.0137568 |
00.5258261 |
ConcurrentDictionary<int,string> |
N |
00.0078668 |
00.0308310 |
05.1309234 |
|
||||
Dictionary<string,int> |
N |
00.0001477 |
00.0173439 |
03.1067780 |
ConcurrentDictionary<string,int> |
N |
00.0184019 |
00.0538895 |
16.7383171 |
Serial |
Do Stuff? |
1,000 |
100,000 |
10,000,000 |
Dictionary<int,string> |
Y |
00.0005953 |
00.0338717 |
02.4231792 |
ConcurrentDictionary<int,string> |
Y |
00.0004088 |
00.0623458 |
07.1167138 |
|
||||
Dictionary<string,int> |
Y |
00.0003674 |
00.0391652 |
04.4576033 |
ConcurrentDictionary<string,int> |
Y |
00.0006012 |
00.0721350 |
16.8413835 |
Parallel |
Do Stuff? |
1,000 |
100,000 |
10,000,000 |
Dictionary<int,string> |
N |
00.0145580 |
00.0392367 |
00.9802224 |
ConcurrentDictionary<int,string> |
N |
00.0012365 |
00.0517408 |
05.8308073 |
|
||||
Dictionary<string,int> |
N |
00.0013542 |
00.0239968 |
03.2670845 |
ConcurrentDictionary<string,int> |
N |
00.0013159 |
00.0725301 |
14.3347261 |
Parallel |
Do Stuff? |
1,000 |
100,000 |
10,000,000 |
Dictionary<int,string> |
Y |
00.0005621 |
00.0689331 |
02.8803307 |
ConcurrentDictionary<int,string> |
Y |
00.0014502 |
00.2194499 |
09.4257171 |
|
||||
Dictionary<string,int> |
Y |
00.0007383 |
00.1126502 |
06.4293967 |
ConcurrentDictionary<string,int> |
Y |
00.0006692 |
00.2526517 |
17.4168156 |
Surmising the Results
Unless someone spots a flaw in my code, when there’s a need for speed, it’s best to use a Dictionary with a lock object instead of a ConcurrentDictionary when the number of items approaches 100,000 or more!
I never would have guessed that the amount of overhead from using a ConcurrentDictionary with its thead-safe methods would be significantly slower when starting to approach hundreds of thousands of objects. After seeing the results, it doesn’t surprise me though.
Should you change your code?
Dictionary Vs ConcurrentDictionary – should you change your code?
When your dictionaries will contain several thousand items and both speed and micro-optimizing every nano-second count, then you should consider implementing a normal Dictionary object and synchronize threads with a lock instead of using ConcurrentDictionary objects. You might consider putting in a few comments saying you know you can use a ConcurrentDictionary, but read this blog and saw it’s faster to implement with a single-threaded Dictionary so people understand why. 🙂
Otherwise, using a ConcurrentDictionary and its associated methods will be more advantageous to use because:
- It is in the framework – is more tested than custom locking routines, and you are not the one who has to maintain the code
- It is scalable: if you are using or going to switch to multithreading, your code is already prepared for it
The Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
using System; using System.Collections.Generic; using System.Collections; using System.Collections.Concurrent; using System.Data; using System.Data.Sql; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Threading; using System.Diagnostics; namespace TestApplication { class Program { static void Main(string[] args) { DateTime end; DateTime start = DateTime.Now; Console.WriteLine("### Overall Start Time: " + start.ToLongTimeString()); Console.WriteLine(); TestFasterToAddToDictionaryOrConcurrentDictionary(1000, false); TestFasterToAddToDictionaryOrConcurrentDictionary(100000, false); TestFasterToAddToDictionaryOrConcurrentDictionary(10000000, false); TestFasterToAddToDictionaryOrConcurrentDictionary(1000, true); TestFasterToAddToDictionaryOrConcurrentDictionary(100000, true); TestFasterToAddToDictionaryOrConcurrentDictionary(10000000, true); end = DateTime.Now; Console.WriteLine(); Console.WriteLine("### Overall End Time: " + end.ToLongTimeString()); Console.WriteLine("### Overall Run Time: " + (end - start)); Console.WriteLine(); Console.WriteLine("Hit Enter to Exit"); Console.ReadLine(); } public static void DoStuff1() { int a = DateTime.Now.Millisecond; double x = double.MaxValue; x = Math.Sqrt(x); x = Math.Sqrt(a); int b = a + DateTime.Now.Millisecond; x = Math.Sqrt(b); x = Math.Round(Math.Sqrt(a) * Math.Sqrt(b)); a = (int)(Math.Log(x) % Math.Log10(x)); b = (int)(Math.Log10(x) / Math.Sqrt(x)); a = (int)(Math.Sqrt(x)); b = (int)(Math.Log(x)); x *= x; x /= Math.Log(b); x -= x; x %= Math.Log10(a); x += x; a = 0; b = 0; x = 0; } //#################################################### //Does a comparison of adding values to a normal and concurrent dictionaries via a //single for loop and parallel for loop. //Code from http://cc.davelozinski.com/c-sharp/dictionary-vs-concurrentdictionary static void TestFasterToAddToDictionaryOrConcurrentDictionary(int numberOfItems, bool doStuff) { Console.WriteLine("######## " + System.Reflection.MethodBase.GetCurrentMethod().Name); Console.WriteLine("Number of Items to add: " + numberOfItems.ToString("#,##0")); Console.WriteLine("Do stuff before add? : " + doStuff.ToString()); Console.WriteLine(); Stopwatch sw = new Stopwatch(); DateTime end = DateTime.Now; DateTime start = DateTime.Now; object lockObject = new object(); Dictionary<int, string> d1 = new Dictionary<int, string>(); Dictionary<string, int> d2 = new Dictionary<string, int>(); ConcurrentDictionary<int, string> cd1 = new ConcurrentDictionary<int, string>(); ConcurrentDictionary<string, int> cd2 = new ConcurrentDictionary<string, int>(); //The arrays of strings and ints we will add. //Purposely will have duplicates to include in test adding where keys already exist. string[] s = new string[numberOfItems]; int[] i = new int[numberOfItems]; //initialize everything Console.WriteLine("Generating int and string arrays."); int z = 10; for (int x = 0; x < s.Length; x++) { if (x % 5 != 0) { s[x] = System.Web.Security.Membership.GeneratePassword(z, x % 5); i[x] = x; } else { s[x] = "Hello World"; i[x] = 555; } z += 1; if (z > 25) z = 10; } Console.WriteLine("###########################################################"); Console.WriteLine("Starting Serial add " + numberOfItems.ToString("#,##0") + " items to Dictionary<int,string> " + (doStuff ? "after DoStuff1" : String.Empty) + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); for (int x = 0; x < numberOfItems; x++) { if (doStuff) DoStuff1(); if (!d1.ContainsKey(i[x])) d1.Add(i[x], s[x]); else d1[i[x]] = s[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Count: " + d1.Count.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); d1.Clear(); //reset for next usage. Make sure we start with clean slate. d1 = null; d1 = new Dictionary<int, string>(); Thread.Sleep(500); Console.WriteLine("###########################################################"); Console.WriteLine("Starting Serial add " + numberOfItems.ToString("#,##0") + " items to ConcurrentDictionary<int,string> " + (doStuff ? "after DoStuff1" : String.Empty) + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); for (int x = 0; x < numberOfItems; x++) { if (doStuff) DoStuff1(); cd1.AddOrUpdate(i[x], s[x], (k, v) => s[x]); } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Count: " + cd1.Count.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); cd1.Clear(); //reset for next usage. Make sure we start with clean slate. cd1 = null; cd1 = new ConcurrentDictionary<int, string>(); Thread.Sleep(500); Console.WriteLine("###########################################################"); Console.WriteLine("Starting Serial add " + numberOfItems.ToString("#,##0") + " items to Dictionary<string,int> " + (doStuff ? "after DoStuff1" : String.Empty) + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); for (int x = 0; x < numberOfItems; x++) { if (doStuff) DoStuff1(); if (!d2.ContainsKey(s[x])) d2.Add(s[x], i[x]); else d2[s[x]] = i[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Count: " + d2.Count.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); d2.Clear(); //reset for next usage. Make sure we start with clean slate. d2 = null; d2 = new Dictionary<string, int>(); Thread.Sleep(500); Console.WriteLine("###########################################################"); Console.WriteLine("Starting Serial add " + numberOfItems.ToString("#,##0") + " items to ConcurrentDictionary<string,int> " + (doStuff ? "after DoStuff1" : String.Empty) + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); for (int x = 0; x < numberOfItems; x++) { if (doStuff) DoStuff1(); cd2.AddOrUpdate(s[x], i[x], (k, v) => i[x]); } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Count: " + cd2.Count.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); cd2.Clear(); //reset for next usage. Make sure we start with clean slate. cd2 = null; cd2 = new ConcurrentDictionary<string, int>(); Thread.Sleep(500); Console.WriteLine("###########################################################"); Console.WriteLine("Starting Parallel add " + numberOfItems.ToString("#,##0") + " items to Dictionary<int,string> " + (doStuff ? "after DoStuff1" : String.Empty) + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); Parallel.For(0, numberOfItems, x => { if (doStuff) DoStuff1(); lock (lockObject) { if (!d1.ContainsKey(i[x])) d1.Add(i[x], s[x]); else d1[i[x]] = s[x]; } }); sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Count: " + d1.Count.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); d1.Clear(); //reset for next usage. Make sure we start with clean slate. d1 = null; d1 = new Dictionary<int, string>(); Thread.Sleep(500); Console.WriteLine("###########################################################"); Console.WriteLine("Starting Parallel add " + numberOfItems.ToString("#,##0") + " items to ConcurrentDictionary<int,string> " + (doStuff ? "after DoStuff1" : String.Empty) + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); Parallel.For(0, numberOfItems, x => { if (doStuff) DoStuff1(); cd1.AddOrUpdate(i[x], s[x], (k, v) => s[x]); }); sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Count: " + cd1.Count.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); cd1.Clear(); //reset for next usage. Make sure we start with clean slate. cd1 = null; cd1 = new ConcurrentDictionary<int, string>(); Thread.Sleep(500); Console.WriteLine("###########################################################"); Console.WriteLine("Starting Parallel add " + numberOfItems.ToString("#,##0") + " items to Dictionary<string,int> " + (doStuff ? "after DoStuff1" : String.Empty) + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); Parallel.For(0, numberOfItems, x => { if (doStuff) DoStuff1(); lock (lockObject) { if (!d2.ContainsKey(s[x])) d2.Add(s[x], i[x]); else d2[s[x]] = i[x]; } }); sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Count: " + d2.Count.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); d2.Clear(); //reset for next usage. Make sure we start with clean slate. d2 = null; d2 = new Dictionary<string, int>(); Thread.Sleep(500); Console.WriteLine("###########################################################"); Console.WriteLine("Starting Parallel add " + numberOfItems.ToString("#,##0") + " items to ConcurrentDictionary<string,int> " + (doStuff ? "after DoStuff1" : String.Empty) + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); Parallel.For(0, numberOfItems, x => { if (doStuff) DoStuff1(); cd2.AddOrUpdate(s[x], i[x], (k, v) => i[x]); }); sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Count: " + cd2.Count.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); cd2.Clear(); //reset for next usage. Make sure we start with clean slate. cd2 = null; cd2 = new ConcurrentDictionary<string, int>(); Thread.Sleep(500); Array.Clear(s, 0, s.Length); s = null; Array.Clear(i, 0, i.Length); i = null; d1.Clear(); d1 = null; d2.Clear(); d2 = null; cd1.Clear(); cd1 = null; cd2.Clear(); cd2 = null; GC.Collect(); } } //class } //namespace |