Skip to content

Instantly share code, notes, and snippets.

@svick
Created August 9, 2019 14:32
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 svick/455c8a825915dd20a631d0dba6394064 to your computer and use it in GitHub Desktop.
Save svick/455c8a825915dd20a631d0dba6394064 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
public class Program
{
static void Main() => BenchmarkRunner.Run<Benchmark<string>>();
}
public class Benchmark<T>
{
[Benchmark]
public IEqualityComparer<T> DirectCast() => (IEqualityComparer<T>)MyComparer.Default;
[Benchmark]
public IEqualityComparer<T> UnsafeAs() => Unsafe.As<IEqualityComparer<T>>(MyComparer.Default);
[Benchmark]
public IEqualityComparer<T> InvariantWrapperCast() => ((Wrapper<IEqualityComparer<T>>)(object)MyComparer.DefaultWrapper).Value;
}
class MyComparer : IEqualityComparer<string>
{
public static IEqualityComparer<string> Default { get; } = new MyComparer();
public static Wrapper<IEqualityComparer<string>> DefaultWrapper { get; } = new Wrapper<IEqualityComparer<string>>(Default);
public bool Equals(string x, string y) => string.Equals(x, y);
public int GetHashCode(string obj) => obj?.GetHashCode() ?? 0;
}
class Wrapper<T>
{
public T Value { get; }
public Wrapper(T value) => Value = value;
}
BenchmarkDotNet=v0.11.5, OS=Windows 10.0.18362
Intel Core i5-2300 CPU 2.80GHz (Sandy Bridge), 1 CPU, 4 logical and 4 physical cores
.NET Core SDK=3.0.100-preview6-012264
  [Host]     : .NET Core 3.0.0-preview6-27804-01 (CoreCLR 4.700.19.30373, CoreFX 4.700.19.30308), 64bit RyuJIT
  DefaultJob : .NET Core 3.0.0-preview6-27804-01 (CoreCLR 4.700.19.30373, CoreFX 4.700.19.30308), 64bit RyuJIT
Method Mean Error StdDev Median
DirectCast 72.1164 ns 0.4131 ns 0.3864 ns 71.9603 ns
UnsafeAs 0.0026 ns 0.0067 ns 0.0062 ns 0.0000 ns
InvariantWrapperCast 2.3557 ns 0.0189 ns 0.0168 ns 2.3577 ns
// * Warnings *
ZeroMeasurement
  Benchmark<String>.UnsafeAs: Default -> The method duration is indistinguishable from the empty method duration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment