I'm curious about the performance characteristics of Parallel.ForEach. Given any valid construct inside a Parallel.ForEach loop, is it always preferable to use Parallel.ForEach over a foreach loop? I'm specifically wondering about the overhead of invoking the Parallel Tasks library on small sets or other edge cases where a foreach loop might be faster. I know the library is pretty smart about when/how to spawn threads...are there cases where it's better to just leave code in a foreach loop, or is the overhead for calling Parallel Tasks generally negligble, so if you can, you should use Parallel.ForEach?
This question is similar and provides good functional difference information but doesn't really speak to performance. Note that I'm ignoring compatibility to .NET <4 as a reason for staying with a foreach:
C#: Any benefit of List<T>.ForEach(...) over plain foreach loop?
Example 2: Parallel. ForEach loop is faster than Traditional Foreach loop.
The execution of Parallel. Foreach is faster than normal ForEach.
There is no lower limit for doing parallel operations. If you have only 2 items to work on but each one will take a while, it might still make sense to use Parallel. ForEach . On the other hand if you have 1000000 items but they don't do very much, the parallel loop might not go any faster than the regular loop.
Since the work in your parallel function is very small, the overhead of the management the parallelism has to do becomes significant, thus slowing down the overall work.
It's not always preferable. For fast loop bodies, Parallel.ForEach can degrade performance. One of the guidelines listed in Parallel Programming Coding Guidelines is to measure both before and after parallelization.
Other useful articles have been published by the parallel computing group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With