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]);

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This says pretty much the opposite. It toally depends on what style of search you are doing. blogs.msdn.com/b/bclteam/archive/2010/06/25/…
5

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."

Comments

3

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.

Comments

2

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);

1 Comment

This can be much faster, but should only be used if this same regex is used more than once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.