Last active
December 2, 2019 16:46
-
-
Save KallDrexx/e13b0761d765dfc6ab8dde869e43340b to your computer and use it in GitHub Desktop.
Vtable benchmark
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 System; | |
using System.Runtime.CompilerServices; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace VtableVsSwitchBenchmark | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<Benchmark>(); | |
} | |
} | |
public class Benchmark | |
{ | |
private readonly IInterfaceObject _interfaceObject = new InterfaceObject3(5); | |
private readonly SingleObject _singleObject = new SingleObject(SingleObject.ObjType.Third, 5); | |
[Benchmark] | |
public int InterfaceTest() => _interfaceObject.GetValue(3); | |
[Benchmark] | |
public int SingleObjectTest() => _singleObject.GetValue(3); | |
} | |
public interface IInterfaceObject | |
{ | |
int GetValue(int input); | |
} | |
public class InterfaceObject1 : IInterfaceObject | |
{ | |
private readonly int _initial; | |
public InterfaceObject1(int initial) | |
{ | |
_initial = initial; | |
} | |
public int GetValue(int input) | |
{ | |
return _initial + input + 3; | |
} | |
} | |
public class InterfaceObject2 : IInterfaceObject | |
{ | |
private readonly int _initial; | |
public InterfaceObject2(int initial) | |
{ | |
_initial = initial; | |
} | |
public int GetValue(int input) | |
{ | |
return _initial + input + 5; | |
} | |
} | |
public class InterfaceObject3 : IInterfaceObject | |
{ | |
private readonly int _initial; | |
public InterfaceObject3(int initial) | |
{ | |
_initial = initial; | |
} | |
public int GetValue(int input) | |
{ | |
return _initial + input + 8; | |
} | |
} | |
public class SingleObject | |
{ | |
public enum ObjType { First, Second, Third } | |
private readonly ObjType _type; | |
private readonly int _initial; | |
public SingleObject(ObjType type, int initial) | |
{ | |
_type = type; | |
_initial = initial; | |
} | |
public int GetValue(int input) | |
{ | |
switch (_type) | |
{ | |
case ObjType.First: return _initial + input + 5; | |
case ObjType.Second: return _initial + input + 6; | |
case ObjType.Third: return _initial + input + 7; | |
default: input + 9; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment