-
-
Save benaadams/a7782d338a67abb71dca0399d76a87ce to your computer and use it in GitHub Desktop.
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; | |
using System; | |
namespace delegate_interface | |
{ | |
public class Program : IFoo | |
{ | |
const int InnerLoopCount = 10000; | |
public Func<int, int, int> Func; | |
public IFoo Foo; | |
public SFoo SFoo; | |
public int X; | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
public int Add(int x, int y) => x + y; | |
[GlobalSetup] | |
public void GlobalSetup() | |
{ | |
Func = Add; | |
Foo = this; | |
SFoo = new SFoo(this); | |
X = 5; | |
} | |
[Benchmark] | |
public int BenchDelegate() => ViaDelegate(X, Func); | |
private static int ViaDelegate(int x, Func<int, int, int> addFunc) | |
{ | |
int res = 0; | |
for (int i = 0; i < InnerLoopCount; ++i) | |
{ | |
res = addFunc(res, x); | |
} | |
return res; | |
} | |
[Benchmark] | |
public int BenchInterface() => ViaInterface(X, Foo); | |
private static int ViaInterface(int x, IFoo foo) | |
{ | |
int res = 0; | |
for (int i = 0; i < InnerLoopCount; ++i) | |
{ | |
res = foo.Add(res, x); | |
} | |
return res; | |
} | |
[Benchmark] | |
public int BenchGenericConstraint() => GenericConstraint(X, this); | |
[Benchmark] | |
public int BenchGenericConstraintInterface() => GenericConstraint(X, Foo); | |
[Benchmark] | |
public int BenchGenericConstraintConcreteStruct() => GenericConstraint(X, SFoo); | |
private static int GenericConstraint<TFoo>(int x, TFoo foo) where TFoo : IFoo | |
{ | |
int res = 0; | |
for (int i = 0; i < InnerLoopCount; ++i) | |
{ | |
res = foo.Add(res, x); | |
} | |
return res; | |
} | |
static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<Program>(); | |
} | |
} | |
public interface IFoo | |
{ | |
int Add(int x, int y); | |
} | |
public struct SFoo : IFoo | |
{ | |
private Program _foo; | |
public SFoo(Program foo) | |
{ | |
_foo = foo; | |
} | |
public int Add(int x, int y) => _foo.Add(x, y); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Being more fair and adding NoInlining
as the call will be too big to inline the calling types are