4 Answers
4

Simply put: For only iterating over a hundred items and performing a small mathematical operation, spawning new threads and waiting for them to complete produces more overhead than just running through the loop would.

From my understanding, calculation within the Parallel.For will be executed in parallel, so must it be faster?

As generally happens when people make sweeping statements about computer performance, there are far more variables at play here, and you can't really make that assumption. For example, inside your for loop, you are doing nothing more than Math.Pow, which the processor can perform very quickly. If this were an I/O intensive operation, requiring each thread to wait a long time, or even if it were a series of processor-intensive operations, you would get more out of Parallel processing (assuming you have a multi-threaded processor). But as it is, the overhead of creating and synchronizing these threads is far greater than any advantage that parallelism might give you.

It's not the number of iterations that's much of a concern (and the TPL won't be spawning new threads, it'll be scheduling them on the ThreadPool, just to be accurate). It's the cost of the operation itself, which in this case is trivial.
–
Adam RobinsonMay 26 '12 at 2:42

Parallel loop processing is beneficial when the operation performed within the loop is relatively costly. All you're doing in your example is calculating an exponent, which is trivial. The overhead of multithreading is far outweighing the gains that you're getting in this case.

The overhead of parallelization is far greater than simply running Math.Pow 100 times sequentially. The others have said this.

More importantly, though, the memory access is trivial in the sequential version, but with the parallel version, the threads have to share memory (resultItems) and that kind of thing will really kill you even if you have a million items.