Created
April 12, 2017 10:48
-
-
Save Mike-E-angelo/d9a3ba07e49abba7dbafb57669c89e42 to your computer and use it in GitHub Desktop.
Basic benchmarks on casting, including with access from a dictionary.
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.Collections.Concurrent; | |
using System.Collections.Generic; | |
using BenchmarkDotNet.Attributes; | |
namespace ClassLibrary1 | |
{ | |
public class CastingBenchmarks | |
{ | |
readonly private static Type Key = typeof(int); | |
readonly private IDictionary<Type, IInterface> _items = new ConcurrentDictionary<Type, IInterface>(); | |
readonly private IInterface _implementation = new Implementation(); | |
public CastingBenchmarks() | |
{ | |
_items.Add(Key, _implementation); | |
} | |
[Benchmark] | |
public IInterface Access() | |
{ | |
IInterface result; | |
return _items.TryGetValue(Key, out result) ? result : null; | |
} | |
[Benchmark] | |
public IInterface<int> AccessCast() | |
{ | |
IInterface result; | |
return _items.TryGetValue(Key, out result) ? (IInterface<int>) result : null; | |
} | |
[Benchmark] | |
public IInterface Instance() => _implementation; | |
[Benchmark] | |
public IInterface<int> InstanceCast() => (IInterface<int>) _implementation; | |
public interface IInterface<in T> | |
{ | |
void Execute(T parameter); | |
} | |
public interface IInterface | |
{ | |
void Execute(object parameter); | |
} | |
private class Implementation : IInterface<int>, IInterface | |
{ | |
public void Execute(int parameter) => parameter.ToString(); | |
public void Execute(object parameter) => Execute((int) parameter); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: