Why does caching make my code run slower?

uncached:

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 

Saved Copy

 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 works slower when I precompile all regular expressions. Not to mention that the iterator on flex should be slower because it needs to do more calculations.

What could be the reason for this?


In fact, if I turn off the Compiled switch, it will work after 8 ms when caching. I thought that β€œcompiled” would compile it when building a regex. If not, when is this done?

+4
source share
2 answers

Regex is actually cached not only for the first use, but also when building (looking at the 4.0 code in the reflector, this may not be so accurate in other frameworks).

So the big differences are here:

  • The latter has a trivial string concatenation that is not included in the former, along with the overhead of building outside the Regex compilation.
  • In the latter case, iteration is repeated than in the previous one.

It is not clear which flex collection is. If this is not a dictionary, then I would not be surprised at this, because the dictionaries are not too terrible at enumeration, and therefore most other collections will beat it.

For the rest, this is really not the case of caching in the latter, since it caches what will already be extracted from the cache in memory, so there is no reason to suspect that the latter will be faster.

+1
source

The problem is with the flag of RegexOptions.Compiled . This actually makes it work much slower. Jeff kind of explains it on his blog . Without this flag, the cached version is much faster.

0
source

Source: https://habr.com/ru/post/1344406/


All Articles