Skip to content

Instantly share code, notes, and snippets.

@wi7a1ian
Last active July 25, 2019 10:37
Show Gist options
  • Save wi7a1ian/5d95a86165d65fb23eb44e086c5368fc to your computer and use it in GitHub Desktop.
Save wi7a1ian/5d95a86165d65fb23eb44e086c5368fc to your computer and use it in GitHub Desktop.
PLINQ having different behaviour than LINQ when trying to obtain first element of filtered collection #csharp
using System;
using System.Linq;
public class Program
{
public static void Main()
{
int ctrS = 0, ctrP = 0, ctrWP = 0;
Enumerable.Range(0, 1_000_000).Where( x => { ++ctrS; return x == 0; }).First();
Enumerable.Range(0, 1_000_000).AsParallel().Where(x => { ++ctrP; return x == 0; }).First();
Enumerable.Range(0, 1_000_000).Where(x => { ++ctrWP; return x == 0; }).AsParallel().First();
Console.WriteLine("How many times was filter predicate executed?");
Console.WriteLine($"sequential = {ctrS}, parallel = {ctrP}, parallel after where: {ctrWP}");
// Produces:
// sequential = 1, parallel = <random>, parallel after where: <max>
// i.e:
// sequential = 1, parallel = 629136, parallel after where: 1000000
// Now try to put some heavy computation like calculating hashes inside filter predicate and you are KEK'd
}
}
@wi7a1ian
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment