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 < 1000; i++) { bool b = regex.IsMatch("The number 1000."); }
Here are the results of a typical run:
Test |
Time taken (in ticks) |
---|---|
1000 * static IsMatch |
21783 |
1000 * instantiated Regex |
14167 |
If you spend a lot of time matching regular expressions...