Skip to content

Instantly share code, notes, and snippets.

@shadow-cs
Created August 20, 2021 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shadow-cs/7b4fc059a616249df5875f1fa0e354a1 to your computer and use it in GitHub Desktop.
Save shadow-cs/7b4fc059a616249df5875f1fa0e354a1 to your computer and use it in GitHub Desktop.
A benchmark for using various methods of passing a delegate
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<Benchmark>();
[MemoryDiagnoser]
public class Benchmark
{
private static int Executor(Func<int> a) => a();
private static int GetAnswerToLifeAndEverything() => 42;
private static readonly Func<int> CachedMethodFunc = GetAnswerToLifeAndEverything;
[Benchmark(Baseline = true)]
public int Lambda() => Executor(() => 42);
[Benchmark]
public int Method() => Executor(GetAnswerToLifeAndEverything);
[Benchmark]
public int CachedMethod() => Executor(CachedMethodFunc);
[Benchmark]
public int MethodWithLambda() => Executor(() => GetAnswerToLifeAndEverything());
[Benchmark]
public int LocalMethod()
{
static int GetAnswerToLifeAndEverythingLocal() => 42;
return Executor(GetAnswerToLifeAndEverythingLocal);
}
[Benchmark]
public int LocalMethodWithLambda()
{
static int GetAnswerToLifeAndEverythingLocal() => 42;
return Executor(() => GetAnswerToLifeAndEverythingLocal());
}
[Benchmark]
public int LambdaWithCapture()
{
var i = GetAnswerToLifeAndEverything();
return Executor(() => i);
}
[Benchmark]
public int LocalNonStaticMethodWithCapture()
{
var i = GetAnswerToLifeAndEverything();
int Returner() => i;
return Executor(Returner);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment