Beware of using RegexOptions.Compiled Regex in some situations

Using the RegexOptions.Compiled option in a Regex instance means that the regular expression is compiled into IL upon creation, which sounds good.

But beware, it can be an expensive operation which highlights itself if the code is called many times. If the Regex instance is reused a lot it makes sense to use this option, but even then beware that the time to create the compiled expression might not be worth it in a one-off scenario. In such cases do not use RegexOptions.Compiled.

Let’s look at some results of a simple test.

In the first example I’m simple creating the Regex in a method and calling the Split method on it, so these results obviously include the creation and use of the object. “Option” denotes whether the Regex was compiled or interpreted and the number column denotes is the number iterations calling we make creating a Regex and using it (time is shown in ms)

[table “” not found /]

Next we’ll create the Regex and reuse it

[table “” not found /]

Obviously what you see in the second table is that when the Regex Split is called a low number of times the performance gain of compiling the expression is minimal, but it gets progressively better the more times the regex is used.

So the lesson is to not use the RegexOptions.Compiled option unless you’re pretty sure the performance hit of creating the Regex isn’t an issue and it will be called a large number of times. All other times do not used RegexOptions.Compiled.

Note: performance tests were carried out on a 32-bit Windows XP machine