3

What would be the right answer if the requirement is that you need to ensure that the expression syntax is evaluated only once when the Regex object is initially instantiated.

var regExpPattern = @"somepatternhere";
  1. Regex.Match(input, regExpPattern);
  2. var evaluate = new Regex(regExpPattern);
  3. var evaluate = new Regex(regExpPattern, RegexOptions.Compiled);

what would be the answer 2 or 3?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Difference between 2 and 3 is in performance. 2 - fast to create object but slow to execute. 3 - slow to create object, fast to execute (compiles regex to IL). – Yuriy Tseretyan Dec 27 '16 at 18:08
  • And is any difference between 1 and 2? –  Dec 27 '16 at 18:09
  • 1
    there's a very good answer [here](http://stackoverflow.com/questions/513412/how-does-regexoptions-compiled-work) on what compiling the regex does – Jonesopolis Dec 27 '16 at 18:09
  • 1
    @sortednoun, it depends. In the 1 case, method seeks an internal cache or regexes and if there is no any, creates a new object and put into cache. If you have many regexes you may end up with constant cache misses. – Yuriy Tseretyan Dec 27 '16 at 18:13
  • Found great explanation of how it works: http://stackoverflow.com/questions/513412/how-does-regexoptions-compiled-work – Yuriy Tseretyan Dec 27 '16 at 18:15

1 Answers1

2

The first one create a new Regex and calls matches() on it:

static MatchCollection Matches(String input, String pattern, RegexOptions options, TimeSpan matchTimeout) {
            return new Regex(pattern, options, matchTimeout, true).Matches(input);
        }

So first and second are almost the same things.

As it have been already said, the last one will be longueur to create but faster to use.

In short, if you plan to use the Regex just once, use 1) or 2). If you plan to run a loop or use the regex a lot of times, prefer the third solution.

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142