views:

165

answers:

4

I've noticed some code that uses the static method:

Regex.IsMatch([someRegexStr], [someInputStr])

Is it worth replacing it with the instance method? Like:

private readonly Regex myRegex = new Regex([someRegexStr]);

...

myRegex.IsMatch([someInputStr]);
+1  A: 

Yes, especially if you can make it a compiled expression. It's slower to construct the Regex object this way, but much faster to use for a net win.

Edit: Potentially (probably++) much faster. There's no requirement that the CLI have a good optimization, but I'm going to guess that Microsoft's certainly is. :D

private readonly Regex myRegex = new Regex([someRegexStr], RegexOptions.Compiled);
280Z28
This can be much faster, but should only be used if this same regex is used more than once.
configurator
I assumed it was based on its `readonly` signature. :)
280Z28
+1  A: 

There is some initial processing that happens when you call the static Regex.IsMatch() method - essentially to validate your regular expression and convert it into a finite state machine representation.

If you plan on running the same regex match multiple times, you are probably better off instantiating a Regex instance, and calling the instance IsMatch() method. You can have the epxression compiled into CLR bytecode using the RegexOptions.Compiled flag, which improves performance even more.

LBushkin
+1  A: 

One of the regular expression optimization recommendations in the following link: Regular Expression Optimization by Jim Mischel

For better performance on commonly used regular expressions, construct a Regex object and call its instance methods.

The article contains interesting topics such as caching regular expressions and compiling regular expressions along with optimization recommendations.

Chansik Im
+1  A: 

The last 15 regular expression internal representations created from the static call are cached.

I talk about this and the internal workings in "How .NET Regular Expressions Really Work."

Jeff Moser