Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static vs. instance versions of Regex.Match in C#

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]);
like image 336
JoelFan Avatar asked Dec 03 '22 15:12

JoelFan


2 Answers

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.

like image 122
Chansik Im Avatar answered Dec 21 '22 23:12

Chansik Im


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

like image 21
Jeff Moser Avatar answered Dec 22 '22 01:12

Jeff Moser