Last active
September 12, 2019 07:03
-
-
Save lahma/cabd5f73b1a37140f6a5a8feb5e54ecb to your computer and use it in GitHub Desktop.
This file contains 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
[MemoryDiagnoser] | |
public class LinqPitfall | |
{ | |
private static readonly int[] source = Enumerable.Range(1, 100_000).ToArray(); | |
private readonly HashSet<int> forbidden = new HashSet<int> | |
{ | |
123, 234, 345, 456, 567, 678, 789, 890, 901, 1000 | |
}; | |
[Benchmark] | |
public int[] Linq() | |
{ | |
return source | |
.Where(x => !forbidden.Contains(x)) | |
.Select(x => x * 2) | |
.ToArray(); | |
} | |
[Benchmark(Baseline = true)] | |
public int[] BoringOld() | |
{ | |
// we can predict a lot of data is in compliance | |
var result = new List<int>(source.Length); | |
foreach (var x in source) | |
{ | |
if (!forbidden.Contains(x)) | |
{ | |
result.Add(x * 2); | |
} | |
} | |
return result.ToArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment