Last active
June 23, 2018 02:18
-
-
Save theunrepentantgeek/9861b043f31d440b8e7183d14a347cc7 to your computer and use it in GitHub Desktop.
Benchmark the relative costs of structs vs primitive types
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; | |
using BenchmarkDotNet.Running; | |
namespace ConsoleApp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<Driver>(); | |
} | |
} | |
[MemoryDiagnoser] | |
public class Driver | |
{ | |
private int Foo(string s) | |
{ | |
return s.GetHashCode(); | |
} | |
private int Foo(WrapString s) | |
{ | |
return s.Value.GetHashCode(); | |
} | |
private int Foo(Wrap<string> s) | |
{ | |
return s.Value.GetHashCode(); | |
} | |
private readonly string _sample = "sample"; | |
[Benchmark] | |
public void Primitive() | |
{ | |
var v = _sample; | |
Foo(v); | |
} | |
[Benchmark] | |
public void UsingStruct() | |
{ | |
var v = new WrapString(_sample); | |
Foo(v); | |
} | |
[Benchmark] | |
public void UsingGenericStruct() | |
{ | |
var v = new Wrap<string>(_sample); | |
Foo(v); | |
} | |
} | |
public readonly struct WrapString | |
{ | |
public readonly string Value; | |
public WrapString(string value) | |
{ | |
Value = value; | |
} | |
} | |
public readonly struct Wrap<T> | |
{ | |
public readonly T Value; | |
public Wrap(T value) | |
{ | |
Value = value; | |
} | |
} | |
} | |
/* | |
Results: | |
Method | Mean | Error | StdDev | Median | Allocated | | |
------------------- |---------:|----------:|----------:|---------:|----------:| | |
Primitive | 6.163 ns | 0.1576 ns | 0.2104 ns | 6.111 ns | 0 B | | |
UsingStruct | 6.124 ns | 0.1970 ns | 0.5394 ns | 5.841 ns | 0 B | | |
UsingGenericStruct | 5.886 ns | 0.0984 ns | 0.0921 ns | 5.894 ns | 0 B | | |
Conclusion: No meaningful difference between the techniques | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment