Parallel LINQ (PLINQ)
2022-02-20
0. What is PLINQ?
- a parallel version of LINQ
- whether it’s going to be parallel will be determined by the PLINQ’s internal analysis on the query
- therefore, performance gain is not guaranteed
- you can force parallelism but it’s not recommended
- using PLINQ has overhead, so don’t overuse it
- make sure to use lock properly along with PLINQ
1. Example
- AsParallel (use PLINQ)
- AsSequential (not using parallel)
- AsOrdered (maintain order)
- ForAll (parallel iteration)
void Main()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var result = Enumerable.Range(0,100)
.AsParallel() // use PLINQ
.Select(Compute)
.Sum();
Console.WriteLine(result);
"------------------------".Dump();
var result2 = Enumerable.Range(0, 100)
.AsParallel() // use PLINQ
.Select(Compute)
.Take(10);
foreach (var r in result2)
{
Console.WriteLine(r); // not ordered
}
"------------------------".Dump();
var result3 = Enumerable.Range(0, 100)
.AsParallel() // use PLINQ
.AsOrdered() // ordered (will add overhead)
.Select(Compute)
.Take(10);
foreach (var r in result3)
{
Console.WriteLine(r); // ordered
}
"------------------------".Dump();
result3.ForAll(Console.WriteLine); // parallel
Console.WriteLine($"It took: {stopwatch.ElapsedMilliseconds}ms to run");
}
static Random random = new Random();
static int Compute(int value)
{
var randomMilliseconds = random.Next(10, 50);
var end = DateTime.Now + TimeSpan.FromMilliseconds(randomMilliseconds);
while (DateTime.Now < end) { }
return value + 100;
}