What is the performance differences between using parallel.foreach and task inside foreach loop?

mting923 picture mting923 · Aug 10, 2013 · Viewed 10.3k times · Source

I would like to know what is the best way or are there any documents/articles that can help me to identify what is the differences of using Parallel.foreach and Task within a normal for each loop, like the following:

case 1 - Parallel.foreach:

Parallel.foreach
{
  // Do SOmething thread safe: parsing an xml and then save 
  // into a DB Server thry respoitory approach
}

case 2 - Task within foreach:

foreach
{
  Task t1 = Task.factory.startNew(()=>
  {
     //Do the same thing as case 1 that is thread safe
  }
}
Task.waitall()
  • I did do my own tests and the result show case 1 perform way better than case 2. The ratio is about like this: sequential vs case 1 vs case 2 = 5s : 1s : 4s

While there are almost a 1:4 on the case 1 and case 2 ? So is it means we should always use parallel.foreach or parallel.for if we want to run in parallel within the loop?

Answer

svick picture svick · Aug 11, 2013

What Parallel.ForEach() does is that it creates a small number of Tasks to process iterations of your loop. Tasks are relatively cheap, but they aren't free, so this tends to improve performance. And the body of your loop executes quickly, the improvement can be really big. This is the most likely explanation for the behavior you're observing.