Skip to content

Instantly share code, notes, and snippets.

@Mike-E-angelo
Created April 12, 2017 10:48
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 Mike-E-angelo/d9a3ba07e49abba7dbafb57669c89e42 to your computer and use it in GitHub Desktop.
Save Mike-E-angelo/d9a3ba07e49abba7dbafb57669c89e42 to your computer and use it in GitHub Desktop.
Basic benchmarks on casting, including with access from a dictionary.
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);
}
}
}
@Mike-E-angelo
Copy link
Author

Results:

// * 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 |    StdErr |    StdDev |     Median |
------------- |----------- |---------- |---------- |----------- |
       Access | 21.5227 ns | 0.0318 ns | 0.1232 ns | 21.5749 ns |
   AccessCast | 86.1340 ns | 0.0804 ns | 0.2897 ns | 86.1233 ns |
     Instance |  0.0091 ns | 0.0028 ns | 0.0108 ns |  0.0000 ns |
 InstanceCast | 63.0500 ns | 0.0762 ns | 0.2850 ns | 62.9240 ns |

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment