Skip to content

Instantly share code, notes, and snippets.

@jackmott
Created September 24, 2025 19:12
Show Gist options
  • Save jackmott/4b6b12f6d05997783a9fa1accd0b2c7b to your computer and use it in GitHub Desktop.
Save jackmott/4b6b12f6d05997783a9fa1accd0b2c7b to your computer and use it in GitHub Desktop.
Linq overhead benchmark
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using System.Collections.Generic;
using System.Linq;
public interface Cool
{
bool IsCool();
}
public abstract class Abs : Cool
{
abstract public int GetId();
abstract public bool IsCool();
}
public class Foo : Abs
{
int id;
public Foo(int id)
{
this.id = id;
}
public override int GetId() => id;
public override bool IsCool() => true;
}
public class Bar : Abs
{
public override int GetId() => 42;
public override bool IsCool() => false;
}
[MemoryDiagnoser]
[SimpleJob(RuntimeMoniker.Net481)]
[SimpleJob(RuntimeMoniker.NetCoreApp31)]
[SimpleJob(RuntimeMoniker.Net60)]
[SimpleJob(RuntimeMoniker.Net80)]
[SimpleJob(RuntimeMoniker.Net90)]
[SimpleJob(RuntimeMoniker.Net10_0)]
public class BenchmarkDemo
{
[Params(1000)]
public int N;
private List<Abs> data;
[GlobalSetup]
public void Setup()
{
data = new List<Abs>(N);
for (int i = 0; i < N; i++)
{
if (i % 2 == 0)
data.Add(new Bar());
else
data.Add(new Foo(i));
}
}
[Benchmark]
public int Linq() =>
data
.Where(x => x.GetId() > 10)
.OrderBy(x => x.GetId())
.Where(x => x.IsCool())
.Select(x => x.GetId())
.Sum();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment