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

Get ASP.NET Site Performance Secrets now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.