Created
August 20, 2021 13:14
-
-
Save shadow-cs/7b4fc059a616249df5875f1fa0e354a1 to your computer and use it in GitHub Desktop.
A benchmark for using various methods of passing a delegate
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
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