Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- */
Add Comment
Please, Sign In to add comment