[Solved] Why is the C# Task Parallel Library code slower than a normal for loop?


To get more accurate results, remove the calls to Console.WriteLine inside both loops. You will still see that parallel loop is slower, because of the reasons stated in the question comments.

To get a better feel for why that is, use instead an overload of Parallel.For from here and set the property ParallelOptions.MaxDegreeOfParallelism to 4 (allow max 4 concurrent operations) or -1 (no restrictions) and the parallel for loop is slower, as expected, because of the thread handling overhead. Now set ParallelOptions.MaxDegreeOfParallelism to 1, meaning only 1 thread will be handling the loop operation. Should result into similar timings now right?

Now the results are closer, but the parallel loop is still slower. It is, i think, because the parallel loop still has to handle threading and interact with the TaskScheduler somehow, where the normal loop does not at all.

I hope this answer gives you some more insight.

solved Why is the C# Task Parallel Library code slower than a normal for loop?