C#: For Vs ForEach Vs While
In this article we’ll benchmark iterating over commonly used collections and data structures with the following loop constructs in C#: For Vs ForEach Vs While.
A List of strings needs to be written to a flat-file; every element in a dictionary object needs to be updated; every row in a DataTable with values from a database needs to be processed.
Every programmer has their own subconscious favorite way of looping over a collection. You can see it in their code. I tend to use a For loop over an Array, List, but usually implement a ForEach iterating over a Dictionary or DataTable.
But that’s when this curious consultant started wondering what construct is best? Hence a showdown in C#: For Vs ForEach Vs While.
Getting Started:
I wrote a C# Console application to test common scenarios.
The code is written in Visual Studio 2013 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.
In a nutshell, the code does the following:
1) Creates 6 types of data structures:
2) Populates them with 100, 50000, 250000 or 5000000 values.
3) Uses one of the following looping constructs:
to iterate over each structure, summing up values, which also verifies every loop ends up with the same total and thus looped the exact same number of iterations.
The code, which is at the end of this blog, assumes all summations will happen with no exception testing.
The single threaded For/ForEach/While loops are bench marked as a group; the Parallel loops are bench marked as their own group.
The exe file was run on Windows 7 64-bit with 32 GB memory.
Start Your Engines!
Before starting, I thought the For loop construct, when it could be used, would win out (although not always by a huge margin).
Let’s see what happened on my machine.
All times are indicated in seconds.milliseconds format and are the averages over 3 runs.
Lower numbers indicate faster performance. Winner marked in green.
Looping over an int[]:
# loops: |
100 |
50,000 |
250,000 |
5,000,000 |
For |
0.0000003 |
0.0001231 |
0.0006048 |
0.0120585 |
ForEach |
0.0000003 |
0.0001038 |
0.0005160 |
0.0104156 |
While |
0.0000003 |
0.0001230 |
0.0006072 |
0.0120238 |
|
||||
Parallel For |
0.0001180 |
0.0002005 |
0.0003407 |
0.0048868 |
Parallel ForEach |
0.0000252 |
0.0001993 |
0.0003707 |
0.0048805 |
Looping over a List
# loops: |
100 |
50,000 |
250,000 |
5,000,000 |
For |
0.0000315 |
0.0074959 |
0.0385195 |
0.8088743 |
ForEach |
0.0000161 |
0.0076712 |
0.0397261 |
0.8358611 |
While |
0.0000165 |
0.0073865 |
0.0379197 |
0.8056663 |
|
||||
Parallel For |
0.0001085 |
0.0010435 |
0.0051182 |
0.1053082 |
Parallel ForEach |
0.0000426 |
0.0011157 |
0.0053677 |
0.1112027 |
Looping over Dictionary
# loops: |
100 |
50,000 |
250,000 |
5,000,000 |
For |
0.0000481 |
0.0087858 |
0.0415127 |
0.8800884 |
ForEach |
0.0000165 |
0.0079057 |
0.0395421 |
0.8451354 |
While |
0.0000181 |
0.0081552 |
0.0416730 |
0.8938068 |
|
||||
Parallel For |
0.0005274 |
0.0011904 |
0.0056796 |
0.1167537 |
Parallel ForEach |
0.0001318 |
0.0060366 |
0.0177860 |
0.3203043 |
Looping over List
# loops: |
100 |
50,000 |
250,000 |
5,000,000 |
For |
0.0000019 |
0.0009697 |
0.0049369 |
0.0996637 |
ForEach |
0.0000027 |
0.0012800 |
0.0052461 |
0.1239720 |
While |
0.0000019 |
0.0009898 |
0.0049500 |
0.0996278 |
|
||||
Parallel For |
0.0000213 |
0.0002819 |
0.0009811 |
0.0170327 |
Parallel ForEach |
0.0000280 |
0.0003510 |
0.0013625 |
0.0247584 |
Looping over DataRow[]:
# loops: |
100 |
50,000 |
250,000 |
5,000,000 |
For |
0.0000781 |
0.0091159 |
0.0259026 |
0.5005515 |
ForEach |
0.0000142 |
0.0053539 |
0.0372900 |
0.5069411 |
While |
0.0000153 |
0.0053526 |
0.0208661 |
0.4759353 |
|
||||
Parallel For |
0.0000548 |
0.0041410 |
0.0077805 |
0.2391097 |
Parallel ForEach |
0.0000473 |
0.0007628 |
0.0201420 |
0.0735779 |
Looping over DataTable:
# loops: |
100 |
50,000 |
250,000 |
5,000,000 |
For |
0.0000485 |
0.0133429 |
0.0708401 |
1.7711373 |
ForEach |
0.0000272 |
0.0066912 |
0.0317441 |
0.6381469 |
While |
0.0000240 |
0.0132004 |
0.0706376 |
1.7711429 |
|
||||
Parallel For |
0.0000560 |
0.0014620 |
0.0082812 |
0.2065083 |
Parallel ForEach |
0.0005665 |
0.0103189 |
0.0518601 |
0.8435395 |
A Few Surprises!
I certainly wouldn’t have picked that a ForEach loop (both single and Parallel) is consistently the fastest way to loop over an int[]! All these years I’ve always used a For loop over something so simple. That may have to chance now. I can only think that this is because it takes longer for a For loop to calculate and access a particular array index than it does a ForEach loop to assign the next value to allocated memory.
I’m perplexed as to why the While loop had the best times over a List and DataRow[]. It also held up well over List.
Obviously the single threaded ForEach is best over a Dictionary
On the Parallel side of things, Parallel.For won out most of the time, which doesn’t surprise me with the multiple simultaneous memory allocations and assignments the Parallel.ForEach has to perform. The anomaly seems to be the DataRow[], where I can only surmise the reasoning is the same as with the basic int[].
What’s interesting is with each of these tests, there always appeared to be one clear-cut winner regardless of the number of loop iterations performed. That is, one looping construct that performed well in a lower number of iterations didn’t falter and held its own up to the 5,000,000 threshold.
Final Say and What You Should Use:
The greatest significant time difference, both single and multi-threaded, was looping over a DataTable: ForEach single threaded or Parallel.For multi-threaded. They proved to be at least 50% faster on average.
The only other significant time differences occurred on the Parallel side of things:
- Looping over the Dictionary
with 50,000+ values, Parallel.For ran in 1/3 the time or faster than a Parallel.ForEach. - Conversely, over a DataRow[] the Parallel.ForEach proved dominant by a wide time difference in most cases.
With everything else, unless the need is there to micro-optimize every single millisecond or you perform your own benchmarking, do yourself the favor and stick with what’s easiest.
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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 |
using System; using System.Collections.Generic; using System.Collections; using System.Collections.Concurrent; 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; //Only uncomment this first group if you want to loop without doing anything else. //ForVsForeachVsWhile(100, false, true); //ForVsForeachVsWhile(50000, false, true); //ForVsForeachVsWhile(250000, false, true); //ForVsForeachVsWhile(5000000, false, true); //ForVsForeachVsWhile(100, true, true); //ForVsForeachVsWhile(50000, true, true); //ForVsForeachVsWhile(250000, true, true); //ForVsForeachVsWhile(5000000, true, true); ForVsForeachVsWhile(100, false, false); ForVsForeachVsWhile(50000, false, false); ForVsForeachVsWhile(250000, false, false); ForVsForeachVsWhile(5000000, false, false); ForVsForeachVsWhile(100, true, false); ForVsForeachVsWhile(50000, true, false); ForVsForeachVsWhile(250000, true, false); ForVsForeachVsWhile(5000000, true, false); 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(); } //######################################################################################################### //For vs ForEach vs While loop //Not accessing items in the collections //Then do it accessing items in the collection //http://www.dotnetperls.com/for-foreach public class ForVsForeachVsWhileTestClass { //Simple custom object for the test since there will be a lot of custom classes out there public Guid g; public string s; public Dictionary<Guid, string> d; public int i = 0; private bool b = false; private decimal dc = 1201.2016M; } //This method does access values in the collections //NumberOfItems - the number of objects to create in each collection and the number of loops to run //DoParallelLoops - test the parallel for and foreach speeds //JustDoPureLooping - do the loops without any other logic static void ForVsForeachVsWhile(int NumberOfItems, bool DoParallelLoops, bool JustDoPureLooping) { Console.WriteLine(); Console.WriteLine("######## " + System.Reflection.MethodBase.GetCurrentMethod().Name); Console.WriteLine("Number of loops: " + NumberOfItems.ToString("#,##0")); Console.WriteLine("DoParallelLoops: " + DoParallelLoops.ToString()); Console.WriteLine("JustDoPureLooping: " + JustDoPureLooping.ToString()); Console.WriteLine(); object lockObject = new object(); long runningTotal = 0; int index = 0; //used for while loops Stopwatch sw = new Stopwatch(); DateTime end = DateTime.Now; DateTime start = DateTime.Now; //the collections to loop over int[] i = new int[NumberOfItems]; List l = new List(NumberOfItems); Dictionary<int, string> d = new Dictionary<int, string>(NumberOfItems); List lf = new List(NumberOfItems); DataTable dt = new DataTable(); DataColumn dtc1 = new DataColumn("Col1"); DataColumn dtc2 = new DataColumn("Col2"); DataColumn dtc3 = new DataColumn("Col3"); DataColumn dtc4 = new DataColumn("Col4"); dtc1.DataType = System.Type.GetType("System.Int32"); dtc2.DataType = System.Type.GetType("System.String"); dtc3.DataType = System.Type.GetType("System.Guid"); dtc4.DataType = System.Type.GetType("System.Double"); dt.Columns.Add(dtc1); dt.Columns.Add(dtc2); dt.Columns.Add(dtc3); dt.Columns.Add(dtc4); DataRow[] dr = new DataRow[NumberOfItems]; //initialize everything for (int x = 0; x < NumberOfItems; x++) { i[x] = x; l.Add(x.ToString()); d.Add(x, x.ToString()); ForVsForeachVsWhileTestClass c = new ForVsForeachVsWhileTestClass(); c.g = Guid.NewGuid(); c.s = x.ToString(); c.i = x; c.d = new Dictionary<Guid, string>(); c.d.Add(c.g, c.s); lf.Add(c); dr[x] = dt.NewRow(); dr[x][dtc1] = x; dr[x][dtc2] = c.g.ToString() + " " + x.ToString(); dr[x][dtc3] = c.g; dr[x][dtc4] = Int32.MaxValue / (x == 0 ? 1 : x); } dt = dr.CopyToDataTable(); //int[] ----------------------------------------------------------------------- runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "For-Loop over int[] at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.For(0, i.Length, () => 0L, (x, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += i[x]; return subtotal; }, (s) => { lock (lockObject) { runningTotal += s; } } ); sw.Stop(); } else { runningTotal = 0; sw.Restart(); for (int x = 0; x < i.Length; x++) { if (!JustDoPureLooping) runningTotal += i[x]; } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "ForEach over int[] at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.ForEach(i, () => 0L, (x, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += x; return subtotal; }, (s) => { lock (lockObject) { runningTotal += s; } } ); sw.Stop(); } else { sw.Restart(); foreach (int x in i) { if (!JustDoPureLooping) runningTotal += x; } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); if (!DoParallelLoops) { runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting While over int[] at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); index = 0; while (index < i.Length) { if (!JustDoPureLooping) runningTotal += i[index]; index += 1; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); } //List ----------------------------------------------------------------------- runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "For-Loop over List at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.For(0, l.Count, () => 0L, (x, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += Convert.ToInt32(l[x]); return subtotal; }, (s) => { lock (lockObject) { runningTotal += s; } } ); sw.Stop(); } else { sw.Restart(); for (int x = 0; x < l.Count; x++) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(l[x]); } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "ForEach over List at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.ForEach(l, () => 0L, (s, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += Convert.ToInt32(s); return subtotal; }, (sum) => { lock (lockObject) { runningTotal += sum; } } ); sw.Stop(); } else { sw.Restart(); foreach (string s in l) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(s); } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); if (!DoParallelLoops) { runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting While over List at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); index = 0; while (index < l.Count) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(l[index]); index += 1; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); } //Dictionary<int,string> ----------------------------------------------------------------------- runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "For-Loop over Dictionary<int, string> at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.For(0, d.Count, () => 0L, (x, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += Convert.ToInt32(d[x]); return subtotal; }, (s) => { lock (lockObject) { runningTotal += s; } } ); sw.Stop(); } else { sw.Restart(); for (int x = 0; x < d.Count; x++) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(d[x]); } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "ForEach over Dictionary<int, string> at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.ForEach(d.Values, () => 0L, (s, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += Convert.ToInt32(s); return subtotal; }, (sum) => { lock (lockObject) { runningTotal += sum; } } ); sw.Stop(); } else { sw.Restart(); foreach (string s in d.Values) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(s); } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); if (!DoParallelLoops) { runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting While over Dictionary<int, string> at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); index = 0; while (index < d.Count) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(d[index]); index += 1; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); } //List ----------------------------------------------------------------------- runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "For-Loop over List at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.For(0, lf.Count, () => 0L, (x, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += lf[x].i; return subtotal; }, (s) => { lock (lockObject) { runningTotal += s; } } ); sw.Stop(); } else { sw.Restart(); for (int x = 0; x < lf.Count; x++) { if (!JustDoPureLooping) runningTotal += lf[x].i; } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "ForEach over List at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.ForEach(lf, () => 0L, (f, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += f.i; return subtotal; }, (s) => { lock (lockObject) { runningTotal += s; } } ); sw.Stop(); } else { sw.Restart(); foreach (ForVsForeachVsWhileTestClass f in lf) { if (!JustDoPureLooping) runningTotal += f.i; } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); if (!DoParallelLoops) { runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting While over List at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); index = 0; while (index < lf.Count) { if (!JustDoPureLooping) runningTotal += lf[index].i; index += 1; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); } //DataRows[] ----------------------------------------------------------------------- runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "For-Loop over DataRows[] at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.For(0, dr.Length, () => 0L, (x, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += Convert.ToInt32(dr[x]["Col1"]); return subtotal; }, (s) => { lock (lockObject) { runningTotal += s; } } ); sw.Stop(); } else { sw.Restart(); for (int x = 0; x < dr.Length; x++) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(dr[x]["Col1"]); } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "ForEach over DataRows[] at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.ForEach(dr, () => 0L, (ddr, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += Convert.ToInt32(ddr["Col1"]); return subtotal; }, (s) => { lock (lockObject) { runningTotal += s; } } ); sw.Stop(); } else { sw.Restart(); foreach (DataRow ddr in dr) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(ddr["Col1"]); } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); if (!DoParallelLoops) { runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting While over DataRows[] at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); index = 0; while (index < dr.Length) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(dr[index]["Col1"]); index += 1; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); } //Datatable ----------------------------------------------------------------------- runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "For-Loop over Datatable at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.For(0, dt.Rows.Count, () => 0L, (x, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += Convert.ToInt32(dt.Rows[x]["Col1"]); return subtotal; }, (s) => { lock (lockObject) { runningTotal += s; } } ); sw.Stop(); } else { sw.Restart(); for (int x = 0; x < dt.Rows.Count; x++) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(dt.Rows[x]["Col1"]); } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting " + (DoParallelLoops ? "Parallel " : "") + "ForEach over Datatable at: " + DateTime.Now.ToLongTimeString()); if (DoParallelLoops) { sw.Restart(); Parallel.ForEach(dt.AsEnumerable(), () => 0L, (dtdr, loopState, subtotal) => { if (!JustDoPureLooping) subtotal += Convert.ToInt32(dtdr["Col1"]); return subtotal; }, (s) => { lock (lockObject) { runningTotal += s; } } ); sw.Stop(); } else { sw.Restart(); foreach (DataRow dtdr in dt.Rows) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(dtdr["Col1"]); } sw.Stop(); } Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); if (!DoParallelLoops) { runningTotal = 0; Console.WriteLine("###########################################################"); Console.WriteLine("Starting While over Datatable at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); index = 0; while (index < dt.Rows.Count) { if (!JustDoPureLooping) runningTotal += Convert.ToInt32(dt.Rows[index]["Col1"]); index += 1; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Running Total: " + runningTotal.ToString("#,##0")); Console.WriteLine("Time: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); } //cleanup if (i != null) Array.Clear(i, 0, i.Length); i = null; if (l != null) l.Clear(); l = null; if (d != null) d.Clear(); d = null; if (lf != null) lf.Clear(); lf = null; if (dr != null) Array.Clear(dr, 0, dr.Length); dr = null; if (dt != null) dt.Clear(); dt.Dispose(); dt = null; GC.Collect(1, GCCollectionMode.Forced, true); } } //class } //namespace |