fork(8) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6. using System.Text.RegularExpressions;
  7. using System.Diagnostics;
  8.  
  9. namespace ca
  10. {
  11. public class Test
  12. {
  13. public static void Main()
  14. {
  15. Regex trimmer = new Regex(@"\s\s+", RegexOptions.Compiled);
  16. Random rng = new Random();
  17. Stopwatch sw = new Stopwatch();
  18. const int n = 5;
  19.  
  20. // random 1mb+ string (it's slow enough...)
  21. StringBuilder ssb = new StringBuilder(1 * 1024 * 1024);
  22. for (int i = 0; i < 1 * 1024 * 1024; ++i)
  23. if (rng.Next(5) == 0)
  24. ssb.Append(new string(' ', rng.Next(20)));
  25. else
  26. ssb.Append((char)(rng.Next(128 - 32) + 32));
  27. string s = ssb.ToString();
  28. StringBuilder tmpbuilder = new StringBuilder(s.Length);
  29. // ===================
  30.  
  31.  
  32.  
  33.  
  34. // ========= regex =========
  35. sw.Start();
  36. for (int i = 0; i < n; ++i)
  37. {
  38. string scopy = s;
  39. scopy = trimmer.Replace(scopy, " ");
  40. }
  41. sw.Stop();
  42. Console.WriteLine("Regex: " + sw.ElapsedMilliseconds + "ms.");
  43.  
  44.  
  45. // ========= stringbuilder =========
  46. sw.Reset(); sw.Start();
  47. for (int i = 0; i < n; ++i)
  48. {
  49. string scopy = s;
  50. bool inspaces = false;
  51. tmpbuilder.Length = 0;
  52.  
  53. for (int k = 0; k < s.Length; ++k)
  54. {
  55. char c = scopy[k];
  56.  
  57. if (inspaces)
  58. {
  59. if (c != ' ')
  60. {
  61. inspaces = false;
  62. tmpbuilder.Append(c);
  63. }
  64. }
  65. else if (c == ' ')
  66. {
  67. inspaces = true;
  68. tmpbuilder.Append(' ');
  69. }
  70. else
  71. tmpbuilder.Append(c);
  72. }
  73. }
  74. sw.Stop();
  75. Console.WriteLine("Stringbuilder: " + sw.ElapsedMilliseconds + "ms.");
  76. }
  77. }
  78. }
Success #stdin #stdout 1.22s 52452KB
stdin
Standard input is empty
stdout
Regex: 1039ms.
Stringbuilder: 68ms.