Last active
July 25, 2019 10:37
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://dotnetfiddle.net/VkPXKV