Search code examples
c#.netlinqparallel-processing

ParallelEnumerable.Range vs Enumerable.Range.AsParallel?


What is the differences between ParallelEnumerable.Range and Enumerable.Range(...).AsParallel()?

ParallelEnumerable.Range creates range partition( best for operations where cpu time is equal foreach item)

where as Enumerable.Range(...).AsParallel() might be executes as range or chunk

Is there any performance difference ? When should I use which ?


Solution

  • If you're performing an operation where it's CPU pressure grows as it iterates then you're going to want to use AsParallel because it can make adjustments as it iterates. However, if it's something that you just need to run in parallel and the operation doesn't create more pressure as it iterates, then use ParallelEnumerable.Range because it can partition the work immediately.

    Reference this article for a more detailed explanation.

    So, let's assume you're performing some complex math in each iteration, and as the input values grow the math takes longer, you're going to want to use AsParallel so that it can make adjustments. But if you use that same option with something like setting a registry setting, you'll see a performance decrease because there is overhead associated with AsParallel that is not necessary.