Program2.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /// dotnet new console
  2. /// dotnet add package BenchmarkDotNet
  3. /// paste this code in Program.cs
  4. /// dotnet publish -r win10-x64 -c Release
  5. /// run an .exe file in publish forder
  6. using System;
  7. using System.Text;
  8. using BenchmarkDotNet.Attributes;
  9. using BenchmarkDotNet.Running;
  10. [MemoryDiagnoser]
  11. public class Program
  12. {
  13. const int Count = 100000;
  14. static void Main(string[] args)
  15. {
  16. BenchmarkRunner.Run<Program>();
  17. }
  18. [Benchmark]
  19. public void StringFormat()
  20. {
  21. var results = new string[Count];
  22. for (int i = 0; i < Count; i++)
  23. {
  24. results[i] = "This is a test #" + i + " with a moment " + DateTime.Now + " so i will " + i + "th time try to concat something";
  25. }
  26. }
  27. [Benchmark]
  28. public void PlusOperator()
  29. {
  30. var results = new string[Count];
  31. for (int i = 0; i < Count; i++)
  32. {
  33. results[i] = String.Format("This is a test #{0} with a moment {1} so i will {0}th time try to concat something", i, DateTime.Now);
  34. }
  35. }
  36. [Benchmark]
  37. public void DollarSign()
  38. {
  39. var results = new string[Count];
  40. for (int i = 0; i < Count; i++)
  41. {
  42. results[i] = $"This is a test #{i} with a moment {DateTime.Now} so i will {i}th time try to concat something";
  43. }
  44. }
  45. [Benchmark]
  46. public void StringBuilder()
  47. {
  48. var results = new string[Count];
  49. for (int i = 0; i < Count; i++)
  50. {
  51. var sb = new StringBuilder(90);
  52. sb.Append("This is a test #");
  53. sb.Append(i);
  54. sb.Append(" with a moment ");
  55. sb.Append(DateTime.Now.ToString());
  56. sb.Append(" so i will ");
  57. sb.Append(i);
  58. sb.Append("th time try to concat something");
  59. results[i] = sb.ToString();
  60. }
  61. }
  62. [Benchmark]
  63. public void ClearableStringBuilder()
  64. {
  65. var results = new string[Count];
  66. var sb = new StringBuilder(90);
  67. for (int i = 0; i < Count; i++)
  68. {
  69. sb.Append("This is a test #");
  70. sb.Append(i);
  71. sb.Append(" with a moment ");
  72. sb.Append(DateTime.Now.ToString());
  73. sb.Append(" so i will ");
  74. sb.Append(i);
  75. sb.Append("th time try to concat something");
  76. results[i] = sb.ToString();
  77. sb.Clear();
  78. }
  79. }
  80. }