Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the guidelines for Parallel.ForEach vs. foreach?

Tags:

.net

.net-4.0

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?

like image 670
Emil Lerch Avatar asked May 13 '10 16:05

Emil Lerch


People also ask

Which is faster parallel ForEach or ForEach?

Example 2: Parallel. ForEach loop is faster than Traditional Foreach loop.

Which is faster ForEach or parallel ForEach C#?

The execution of Parallel. Foreach is faster than normal ForEach.

Should you use parallel 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.

Why is parallel ForEach slower?

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.


1 Answers

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.

like image 130
Stephen Cleary Avatar answered Oct 28 '22 06:10

Stephen Cleary