Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performances of PLINQ vs TPL

I have some DB operations to perform and I tried using PLINQ:

someCollection.AsParallel()
              .WithCancellation(token)
              .ForAll(element => ExecuteDbOperation(element))

And I notice it is quite slow compared to:

var tasks = someCollection.Select(element =>
                                    Task.Run(() => ExecuteDbOperation(element), token))
                          .ToList()

await Task.WhenAll(tasks)

I prefer the PLINQ syntax, but I am forced to use the second version for performances.

Can someone explain the big difference in performances?

like image 658
Stefano d'Antonio Avatar asked Sep 02 '25 16:09

Stefano d'Antonio


1 Answers

My supposition that this is because of the number of threads created.

In the first example this number will be roughly equal to the number of cores of your computer. By contrast, the second example will create as many threads as someCollection has elements. For IO operation that's generally more efficient.

The Microsoft guide "Patterns_of_Parallel_Programming_CSharp" recommends for IO operation to create more threads than default (p. 33):

var addrs = new[] { addr1, addr2, ..., addrN };
var pings = from addr in addrs.AsParallel().WithDegreeOfParallelism(16)
select new Ping().Send(addr);
like image 173
Disappointed Avatar answered Sep 04 '25 06:09

Disappointed