Skip to content

Instantly share code, notes, and snippets.

@lahma
Last active September 12, 2019 07:03
Show Gist options
  • Save lahma/cabd5f73b1a37140f6a5a8feb5e54ecb to your computer and use it in GitHub Desktop.
Save lahma/cabd5f73b1a37140f6a5a8feb5e54ecb to your computer and use it in GitHub Desktop.
[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