Created
March 11, 2017 17:32
-
-
Save bdrupieski/bf6fefac8da3566646afec612ac151ab to your computer and use it in GitHub Desktop.
Performance and correctness comparison between foreach and Parallel.ForEach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Threading.Tasks; | |
namespace App | |
{ | |
/// <summary> | |
/// This snippet shows a performance and correctness comparison between | |
/// foreach and Parallel.ForEach when adding a small number of objects to a | |
/// List{T}. | |
/// | |
/// For a handful of items using a simple foreach loop is much faster and | |
/// using Parallel.ForEach is much slower. Adding items to List{T} | |
/// is also not thread-safe, so using Parallel.ForEach sometimes results in | |
/// not adding all of the items you intended to add. | |
/// </summary> | |
public static class CompareForeachToParallelForeach | |
{ | |
private static readonly int Runs = 1000000; | |
private static readonly List<string> Parameters = new List<string> | |
{ | |
"A", | |
"B", | |
"C", | |
"D" | |
}; | |
public static void DoIt() | |
{ | |
var sw = Stopwatch.StartNew(); | |
ParallelForEach(); | |
sw.Stop(); | |
var millisecondsParallelForEach = sw.ElapsedMilliseconds; | |
Console.WriteLine($"{millisecondsParallelForEach} ms using Parallel.ForEach"); | |
sw = Stopwatch.StartNew(); | |
ForEach(); | |
sw.Stop(); | |
var millisecondsForEach = sw.ElapsedMilliseconds; | |
Console.WriteLine($"{millisecondsForEach} ms using ForEach"); | |
Console.WriteLine($"Parallel.ForEach takes {millisecondsParallelForEach / millisecondsForEach}x longer than ForEach"); | |
} | |
private static void ParallelForEach() | |
{ | |
int numTimes = 0; | |
for (int i = 0; i < Runs; i++) | |
{ | |
var request = new List<string>(); | |
Parallel.ForEach(Parameters, parameter => | |
{ | |
request.Add(parameter); | |
}); | |
if (request.Count != Parameters.Count) | |
{ | |
numTimes++; | |
} | |
} | |
Console.WriteLine($"The number of items in the list is different {numTimes} times for {nameof(ParallelForEach)}"); | |
} | |
private static void ForEach() | |
{ | |
int numTimes = 0; | |
for (int i = 0; i < Runs; i++) | |
{ | |
var request = new List<string>(); | |
foreach (var parameter in Parameters) | |
{ | |
request.Add(parameter); | |
} | |
if (request.Count != Parameters.Count) | |
{ | |
numTimes++; | |
} | |
} | |
Console.WriteLine($"The number of items in the list is different {numTimes} times for {nameof(ForEach)}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment