Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Basic benchmarks around implicit/explicit contra/covariant casting.
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;
}
}
}
Owner

Mike-EEE commented Apr 13, 2017

Reference: https://www.danielcrabtree.com/blog/191/casting-to-ienumerable-t-is-two-orders-of-magnitude-slower

// * Summary *

BenchmarkDotNet=v0.10.3.0, OS=Microsoft Windows NT 6.2.9200.0
Processor=Intel(R) Core(TM) i7-4820K CPU 3.70GHz, ProcessorCount=8
Frequency=3613280 Hz, Resolution=276.7569 ns, Timer=TSC
  [Host]     : Clr 4.0.30319.42000, 32bit LegacyJIT-v4.6.1637.0
  DefaultJob : Clr 4.0.30319.42000, 32bit LegacyJIT-v4.6.1637.0


   Method |       Mean |    StdDev | Scaled | Scaled-StdDev |
--------- |----------- |---------- |------- |-------------- |
   Direct | 11.6787 ns | 0.1127 ns |   1.00 |          0.00 |
 Implicit | 11.7160 ns | 0.0766 ns |   1.00 |          0.01 |
 Explicit | 79.9238 ns | 0.6084 ns |   6.84 |          0.08 |

// ***** BenchmarkRunner: End *****
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment