Skip to content

Instantly share code, notes, and snippets.

@KallDrexx
Last active December 2, 2019 16:46
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 KallDrexx/e13b0761d765dfc6ab8dde869e43340b to your computer and use it in GitHub Desktop.
Save KallDrexx/e13b0761d765dfc6ab8dde869e43340b to your computer and use it in GitHub Desktop.
Vtable benchmark
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