Guest User

Untitled

a guest
Jun 24th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. using BenchmarkDotNet.Attributes;
  2. using BenchmarkDotNet.Running;
  3.  
  4. namespace ConsoleApp
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. BenchmarkRunner.Run<Driver>();
  11. }
  12. }
  13.  
  14. [MemoryDiagnoser]
  15. public class Driver
  16. {
  17. private int Foo(string s)
  18. {
  19. return s.GetHashCode();
  20. }
  21.  
  22. private int Foo(WrapString s)
  23. {
  24. return s.Value.GetHashCode();
  25. }
  26.  
  27. private int Foo(Wrap<string> s)
  28. {
  29. return s.Value.GetHashCode();
  30. }
  31.  
  32. private readonly string _sample = "sample";
  33.  
  34. [Benchmark]
  35. public void Primitive()
  36. {
  37. var v = _sample;
  38. Foo(v);
  39. }
  40.  
  41. [Benchmark]
  42. public void UsingStruct()
  43. {
  44. var v = new WrapString(_sample);
  45. Foo(v);
  46. }
  47.  
  48. [Benchmark]
  49. public void UsingGenericStruct()
  50. {
  51. var v = new Wrap<string>(_sample);
  52. Foo(v);
  53. }
  54. }
  55.  
  56. public readonly struct WrapString
  57. {
  58. public readonly string Value;
  59.  
  60. public WrapString(string value)
  61. {
  62. Value = value;
  63. }
  64. }
  65.  
  66. public readonly struct Wrap<T>
  67. {
  68. public readonly T Value;
  69.  
  70. public Wrap(T value)
  71. {
  72. Value = value;
  73. }
  74. }
  75.  
  76. }
  77.  
  78. /*
  79. Results:
  80. Method | Mean | Error | StdDev | Median | Allocated |
  81. ------------------- |---------:|----------:|----------:|---------:|----------:|
  82. Primitive | 6.163 ns | 0.1576 ns | 0.2104 ns | 6.111 ns | 0 B |
  83. UsingStruct | 6.124 ns | 0.1970 ns | 0.5394 ns | 5.841 ns | 0 B |
  84. UsingGenericStruct | 5.886 ns | 0.0984 ns | 0.0921 ns | 5.894 ns | 0 B |
  85.  
  86. Conclusion: No meaningful difference between the techniques
  87. */
Add Comment
Please, Sign In to add comment