I wrote a little program to check the performance of Sum()
working on an AsParallel()
enumeration (i.e. PLINQ).
First, I generate an IEnumerable
. The range is not particularly large because then the LINQ Sum()
would result in an overflow.
IEnumerable<int> range = Enumerable.Range(1, 30000);
My first benchmark is performed using a regular loop:
var stopwatch = new Stopwatch();
stopwatch.Start();
int total = 0;
foreach(int x in range)
{
total += x;
}
stopwatch.Stop();
Console.WriteLine("Sum 1: {0}; time: {1}", total, stopwatch.Elapsed);
My second benchmark uses LINQ Sum()
:
stopwatch.Restart();
int total2 = range.Sum();
stopwatch.Stop();
Console.WriteLine("Sum 2: {0}; time: {1}", total2, stopwatch.Elapsed);
My third benchmark uses PLINQ Sum()
:
stopwatch.Restart();
int total3 = range.AsParallel().Sum();
stopwatch.Stop();
Console.WriteLine("Sum 3: {0}; time: {1}", total3, stopwatch.Elapsed);
Here are some results:
Sum 1: 450015000; time: 00:00:00.0004210
Sum 2: 450015000; time: 00:00:00.0003545
Sum 3: 450015000; time: 00:00:00.0427375
Why is the PLINQ version (Sum 3) so much slower than the others? Also, why is the LINQ Sum()
(Sum 2) faster than the plain loop (Sum 1)?