Regular Expressions using RegexOptions.IgnoreCase slower than inline case insensitive pattern syntax in .NET 6

RegexOptions.IgnoreCase often offers better readability and expression of intent than inline pattern matching. We can see examples of the two approaches below in the _r1 and _r2 regex variables. Note however that while these might be functionality equivalent they are implemented differently up to .NET 7.

The inline version will be compiled to something like

(c == 'A') | (c == 'a') to match [Aa]

whereas the RegexOptions.IgnoreCase version will be compiled to call ToLower() on each character resulting in extra overhead. The performance differences on my machine are shown below.

Note we can see the issue is fixed in .NET 7.

Click on the image for a larger view in a new window…

Always focus on readability for the next developer first BUT if you’re in a really performance sensitive hot path and using .NET 6 keep the above in mind …

Leave a Reply

Your email address will not be published.