Skip to content

Instantly share code, notes, and snippets.

@benaadams
Forked from stephentoub/DelegateVsInterface
Last active October 9, 2019 13:57
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 benaadams/a7782d338a67abb71dca0399d76a87ce to your computer and use it in GitHub Desktop.
Save benaadams/a7782d338a67abb71dca0399d76a87ce to your computer and use it in GitHub Desktop.
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);
}
}
@benaadams
Copy link
Author

Method Mean Error
BenchDelegate 19.146 us 0.4040 us
BenchInterface 25.310 us 0.4920 us
BenchGenericConstraint 25.409 us 0.5692 us
BenchGenericConstraintInterface 25.685 us 0.5032 us
BenchGenericConstraintConcreteStruct 3.117 us 0.0608 us

Being more fair and adding NoInlining

[MethodImpl(MethodImplOptions.NoInlining)]
public int Add(int x, int y) => x + y;

as the call will be too big to inline the calling types are

Method Mean Error
BenchDelegate 17.15 us 0.1082 us
BenchInterface 23.08 us 0.1620 us
BenchGenericConstraint 23.35 us 0.3040 us
BenchGenericConstraintInterface 23.38 us 0.2970 us
BenchGenericConstraintConcreteStruct 15.16 us 0.3024 us

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment