Program.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Text;
  9. using BenchmarkDotNet;
  10. using BenchmarkDotNet.Attributes;
  11. using BenchmarkDotNet.Running;
  12. [MemoryDiagnoser]
  13. public class Program
  14. {
  15. const int Count = 10000;
  16. static void Main(string[] args)
  17. {
  18. var summary = BenchmarkRunner.Run<Program>();
  19. }
  20. [Benchmark]
  21. public void PlusOperatorConcatTest()
  22. {
  23. string str = "";
  24. for (int i = 0; i < Count; i++)
  25. {
  26. str += "A";
  27. }
  28. }
  29. [Benchmark]
  30. public void FixedListConcatTest()
  31. {
  32. var parts = new List<string>(Count);
  33. for (int i = 0; i < Count; i++)
  34. {
  35. parts.Add("A");
  36. }
  37. var str = String.Join(String.Empty, parts);
  38. }
  39. [Benchmark]
  40. public void UnfixedListConcatTest()
  41. {
  42. var parts = new List<string>();
  43. for (int i = 0; i < Count; i++)
  44. {
  45. parts.Add("A");
  46. }
  47. var str = String.Join(String.Empty, parts);
  48. }
  49. [Benchmark]
  50. public void FixedStringBuilderTest()
  51. {
  52. var sb = new StringBuilder(Count);
  53. for (int i = 0; i < Count; i++)
  54. {
  55. sb.Append("A");
  56. }
  57. var str = sb.ToString();
  58. }
  59. [Benchmark]
  60. public void UnfixedStringBuilderTest()
  61. {
  62. var sb = new StringBuilder();
  63. for (int i = 0; i < Count; i++)
  64. {
  65. sb.Append("A");
  66. }
  67. var str = sb.ToString();
  68. }
  69. }