Create a gist now

Instantly share code, notes, and snippets.

LinqOptimisation Benchmarks - Count
namespace LinqOptimisationBenchmarks
{
[Config(typeof (BenchmarkConfig))]
public class CountBenchmarks
{
private static readonly int[] items;
static CountBenchmarks()
{
items = Enumerable.Range(0, 1000).ToArray();
}
[Benchmark(Baseline = true)]
public int Iterative()
{
var counter = 0;
foreach (var item in items)
{
if (item % 10 == 0)
counter += item;
}
return counter;
}
[Benchmark]
[Shaman.Runtime.NoLinqRewrite] // Yay, this works!!
public int Linq()
{
return items.Where(i => i % 10 == 0).Count();
}
[Benchmark]
public int RoslynLinqRewrite()
{
return RoslynLinqRewrite_ProceduralLinq1(items);
}
int RoslynLinqRewrite_ProceduralLinq1(int[] _linqitems)
{
if (_linqitems == null)
throw new System.ArgumentNullException();
var _count = 0;
for (int _index = 0; _index < _linqitems.Length; _index++)
{
var _linqitem = _linqitems[_index];
if (_linqitem % 10 == 0)
{
_count++;
}
}
return _count;
}
private static readonly Func<int[], int> compiledSumQuery = Extensions.Compile<int[], int>(ps => ps.AsQueryExpr().Where(i => i % 10 == 0).Count());
[Benchmark]
[Shaman.Runtime.NoLinqRewrite]
public int LinqOptimiser()
{
return compiledSumQuery(items);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment