Non-cached:
var sw = Stopwatch.StartNew();
foreach (var str in testStrings)
{
foreach (var pair in flex)
{
if (Regex.IsMatch(str, "^(" + pair.Value + ")$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture))
;
}
}
Console.WriteLine("\nRan in {0} ms", sw.ElapsedMilliseconds); // 76 ms
Cached
var cache = flex.ToDictionary(p => p.Key, p => new Regex("^(" + p.Value + ")$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled));
var sw = Stopwatch.StartNew();
foreach (var str in testStrings)
{
foreach (var pair in cache)
{
if(pair.Value.IsMatch(str))
;
}
}
Console.WriteLine("\nRan in {0} ms", sw.ElapsedMilliseconds); // 263 ms
I don't know why it's running slower when I pre-compile all the regexes. Not to mention the iterator on flex should be slower too, because it needs to do more calculations.
What could be causing this?
Actually, if I take off the Compiled
switch it runs in 8 ms when cached. I thought "compiled" would compile it upon construction of the regex. If not, when does it do so?