fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Linq;
  7.  
  8. public class Test
  9. {
  10. public static void Main()
  11. {
  12. var random = new Random(7);
  13. var sb = new StringBuilder();
  14. for (int i = 0; i < 80; i++)
  15. {
  16. sb.Append((char)random.Next('a', 'z'));
  17. }
  18.  
  19. var input = sb.ToString();
  20. TimeIt(new RegexSolution(), input);
  21.  
  22. System.GC.Collect();
  23. System.GC.WaitForPendingFinalizers();
  24.  
  25. TimeIt(new IteratorSolution(), input);
  26. }
  27.  
  28. private static void TimeIt(ISolution solution, string input)
  29. {
  30. // Warmup.
  31. var x = solution.ToBuckets(input).Count();
  32. var sw = Stopwatch.StartNew();
  33. for (int i = 0; i < 100000; i++)
  34. {
  35. x += solution.ToBuckets(input).Count();
  36. }
  37. sw.Stop();
  38. Console.WriteLine("{0}, {1}", solution.Name, x);
  39. Console.WriteLine(sw.Elapsed);
  40. }
  41.  
  42. private interface ISolution
  43. {
  44. string Name { get; }
  45.  
  46. IEnumerable<string> ToBuckets(string input);
  47. }
  48.  
  49. private class RegexSolution : ISolution
  50. {
  51. public string Name
  52. {
  53. get { return "Regex"; }
  54. }
  55.  
  56. public IEnumerable<string> ToBuckets(string input)
  57. {
  58. return Regex.Match(input, "^(?<bucket>.{4})+$")
  59. .Groups["bucket"].Captures
  60. .Cast<Capture>()
  61. .Select(capture => capture.Value);
  62. }
  63. }
  64.  
  65. private class IteratorSolution : ISolution
  66. {
  67. public string Name
  68. {
  69. get { return "Iterator"; }
  70. }
  71.  
  72. public IEnumerable<string> ToBuckets(string input)
  73. {
  74. const int Length = 4;
  75. if (input == null)
  76. {
  77. throw new ArgumentNullException("input");
  78. }
  79.  
  80. if (input.Length % Length != 0)
  81. {
  82. throw new ArgumentException(string.Format("Argument length must be a multiple of {0}", Length));
  83. }
  84.  
  85. for (var i = 0; i < input.Length; i += Length)
  86. {
  87. yield return input.Substring(i, Length);
  88. }
  89. }
  90. }
  91. }
Success #stdin #stdout 2.76s 34416KB
stdin
Standard input is empty
stdout
Regex, 2000020
00:00:02.4985534
Iterator, 2000020
00:00:00.1828342