Skip to content

Instantly share code, notes, and snippets.

@stephentoub
Created September 13, 2019 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stephentoub/a75ac6f7337a18df68bd23f4f682d926 to your computer and use it in GitHub Desktop.
Save stephentoub/a75ac6f7337a18df68bd23f4f682d926 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 int X;
public int Add(int x, int y) => x + y;
[GlobalSetup]
public void GlobalSetup()
{
Func = Add;
Foo = this;
X = 5;
}
[Benchmark]
public int BenchDelegate()
{
int x = X;
Func<int, int, int> addFunc = Func;
int res = 0;
for (int i = 0; i < InnerLoopCount; ++i)
{
res = addFunc(res, x);
}
return res;
}
[Benchmark]
public int BenchInterface()
{
int x = X;
IFoo foo = Foo;
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment