fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using System.Threading.Tasks;
  8.  
  9. namespace RegexVsStrings
  10. {
  11. class Program
  12. {
  13. static TimeSpan ProfileIt(Func<int> a)
  14. {
  15. const int numberOfRuns = 10;
  16. a();
  17.  
  18. int total = 0;
  19. var sw = Stopwatch.StartNew();
  20. for (int i = 0; i < numberOfRuns; i++)
  21. total += a();
  22. sw.Stop();
  23.  
  24. Console.WriteLine("Total result: " + total);
  25.  
  26. return sw.Elapsed;
  27. }
  28.  
  29. static List<string> data;
  30.  
  31. static Random r = new Random();
  32.  
  33. static string RandomString()
  34. {
  35. var l = r.Next(2, 50);
  36. return new string(Enumerable.Range(0, l).Select(_ => (char)('a' + r.Next(25))).ToArray());
  37. }
  38.  
  39. static Regex regex = new Regex(@"^music(?:(?>[^\.\n]+)|\.)*\.(?:mp3|wav)$", RegexOptions.Multiline | RegexOptions.Compiled);
  40.  
  41. static int TestRegex()
  42. {
  43. var count = 0;
  44. foreach (var s in data)
  45. if (regex.IsMatch(s))
  46. count++;
  47. return count;
  48. }
  49.  
  50. static int TestStringCompare()
  51. {
  52. var count = 0;
  53. foreach (var s in data)
  54. if (s.StartsWith("music") && (s.EndsWith("mp3") || s.EndsWith("wav")))
  55. count++;
  56. return count;
  57. }
  58.  
  59. static void Main(string[] args)
  60. {
  61. data = Enumerable.Range(0, 500)
  62. .Select(n => new[]
  63. {
  64. "music" + RandomString() + "mp3",
  65. "music" + RandomString() + "wav",
  66. "trampampam" + RandomString() + "tralala",
  67. "music" + RandomString() + "tralala",
  68. "lalafa" + RandomString() + "mp3"
  69. })
  70. .SelectMany(s => s)
  71. .ToList();
  72.  
  73. var t1 = ProfileIt(TestRegex);
  74. var t2 = ProfileIt(TestStringCompare);
  75. Console.WriteLine("Regex: " + t1);
  76. Console.WriteLine("String compare: " + t2);
  77. }
  78. }
  79. }
Success #stdin #stdout 0.69s 25848KB
stdin
Standard input is empty
stdout
Total result: 0
Total result: 10000
Regex: 00:00:00.0549839
String compare: 00:00:00.4220896