Created
April 13, 2017 06:20
-
-
Save Mike-E-angelo/43ca8807eb3e379581136783bce39213 to your computer and use it in GitHub Desktop.
Basic benchmarks around implicit/explicit contra/covariant casting.
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; | |
namespace ClassLibrary1 | |
{ | |
public class ImplicitCastingBenchmarks | |
{ | |
readonly private IInterface<string> _sut = new Implementation(); | |
readonly private IInterface<object> _obj; | |
public ImplicitCastingBenchmarks() | |
{ | |
_obj = _sut; | |
} | |
[Benchmark(Baseline = true)] | |
public void Direct() => Specific(_sut); | |
[Benchmark] | |
public void Implicit() => General(_sut); | |
[Benchmark] | |
public void Explicit() => Specific((IInterface<string>)_obj); | |
private static void Specific(IInterface<string> parameter) => parameter.ToString(); | |
private static void General(IInterface<object> parameter) => parameter.ToString(); | |
private interface IInterface<out T> | |
{ | |
T Get(); | |
} | |
private class Implementation : IInterface<string> | |
{ | |
public string Get() => string.Empty; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: https://www.danielcrabtree.com/blog/191/casting-to-ienumerable-t-is-two-orders-of-magnitude-slower