Created
September 13, 2019 21:38
-
-
Save stephentoub/a75ac6f7337a18df68bd23f4f682d926 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 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