Last active
August 10, 2017 08:04
-
-
Save dadhi/e72e3489ce52d91566d23e9622d48b5d to your computer and use it in GitHub Desktop.
Benchmark of Delegate vs Interface Struct implementation
This file contains hidden or 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 System; | |
using BenchmarkDotNet.Attributes; | |
namespace Playground | |
{ | |
[MemoryDiagnoser] | |
public class DelegateVsInterfaceStruct | |
{ | |
[Params(10, 100, 1000)] public int ArraySize; | |
[Benchmark] | |
public object ApplyDelegate() | |
{ | |
Func<int, int> inc = n => n + 1; | |
var nums = new int[ArraySize]; | |
for (var i = 0; i < nums.Length; i++) | |
nums[i] = inc(i); | |
return nums; | |
} | |
[Benchmark(Baseline = true)] | |
public object ApplyStruct() | |
{ | |
var inc = new Inc(); | |
var nums = new int[ArraySize]; | |
for (var i = 0; i < nums.Length; i++) | |
nums[i] = inc.Apply(i); | |
return nums; | |
} | |
} | |
public interface IApply<in TIn, out TOut> | |
{ | |
TOut Apply(TIn value); | |
} | |
public struct Inc : IApply<int, int> | |
{ | |
public int Apply(int value) => value + 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment