10 Jan

Parallel.ForEach vs foreach

So a couple of days ago I came in contact with the Parallel.ForEach.

At first I was very enthusiastically changing all the foreach loops in my test project, but then I found out there is more to it then just simply changing everything…

What does it do?

foreach

This is the typical foreach that everyone knows. Data is going to be looped one by one.

foreach (var item in list)
{
   DoFunction(item);
}


The “problem” with this foreach is that item #1.000.000 has to wait until the previous 999.999 items are done. This can take a while and still the server isn’t overloading itself with work because it has no problem handling one item at a time.

Parallel.ForEach

Parallel.ForEach(list, item => 
{
    DoFunction(item);
});

The basics of Parallel.ForEach are the same as for the normal foreach loop. It’s going to loop through a collection of items. The big difference is that it does it in Parallel (hence the name). Which means it’s looping through all items at once without waiting for the previous item to complete. However any code coming behind the parallel loop will only be executed once the whole loop is completed.

What to watch our for when using Parallel.ForEach

Database calls

Try to avoid database calls in your Parallel.ForEach loop. Especially with Entity Framework since EF is known not to be thread safe.

Ordered lists

If you’re processing an ordered list and outputs it back in an other list, make sure to re-order your output after the Parallel.ForEach loop. Since the loop takes on every object at the same time. It will not keep the order.

Speed

Although most of the times Parallel.ForEach is faster, it does not mean it always is.
A simple sum or multiplication would normally be faster in a normal foreach because of the overhead being created when introducing parallelism.

Conclusion

foreach

  • Iterations takes place sequentially one by one
  • foreach loop is run from a single Thread
  • foreach loop is defined in every framework of .NET
  • Execution is slower (with complex loops)

Parallel.Foreach

  • Execution takes place in parallel way
  • Parallel.ForEach uses multiple Threads
  • Parallel.ForEach is defined in .Net 4.0 and above frameworks
  • Execution is faster (most of the times)


Sources

Leave a Reply

Your email address will not be published. Required fields are marked *