using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace RegexVsStrings
{
class Program
{
static TimeSpan ProfileIt(Func<int> a)
{
const int numberOfRuns = 10;
a();
int total = 0;
var sw = Stopwatch.StartNew();
for (int i = 0; i < numberOfRuns; i++)
total += a();
sw.Stop();
Console.WriteLine("Total result: " + total);
return sw.Elapsed;
}
static List<string> data;
static Random r = new Random();
static string RandomString()
{
var l = r.Next(2, 50);
return new string(Enumerable.Range(0, l).Select(_ => (char)('a' + r.Next(25))).ToArray());
}
static Regex regex = new Regex(@"^music(?:(?>[^\.\n]+)|\.)*\.(?:mp3|wav)$", RegexOptions.Multiline | RegexOptions.Compiled);
static int TestRegex()
{
var count = 0;
foreach (var s in data)
if (regex.IsMatch(s))
count++;
return count;
}
static int TestStringCompare()
{
var count = 0;
foreach (var s in data)
if (s.StartsWith("music") && (s.EndsWith("mp3") || s.EndsWith("wav")))
count++;
return count;
}
static void Main(string[] args)
{
data = Enumerable.Range(0, 500)
.Select(n => new[]
{
"music" + RandomString() + "mp3",
"music" + RandomString() + "wav",
"trampampam" + RandomString() + "tralala",
"music" + RandomString() + "tralala",
"lalafa" + RandomString() + "mp3"
})
.SelectMany(s => s)
.ToList();
var t1 = ProfileIt(TestRegex);
var t2 = ProfileIt(TestStringCompare);
Console.WriteLine("Regex: " + t1);
Console.WriteLine("String compare: " + t2);
}
}
}