O'Reilly logo

ASP.NET Site Performance Secrets by Matt Perdeck

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Regex instantiation

When matching a string against a regular expression, you have a few choices. You can first instantiate a Regex object with the regular expression and then call the IsMatch method on that object, passing in the string. Also, you can call the static Regex.IsMatch, which takes both the regular expression and the string.

If you repeat the same match many times, you will save CPU cycles by instantiating the Regex object outside the loop, rather than using the static version of IsMatch.

Here is a loop using the static IsMatch:

for (int i = 0; i < 1000; i++)
{
bool b = (Regex.IsMatch("The number 1000.", @"\d+"));
}

And here its counterpart which instantiates Regex outside the loop:

Regex regex = new Regex(@"\d+"); for (int i = 0; i ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required