Search code examples
.netregexcase-sensitive

.net Regex Performance consideration: Use (partial or global) case-insensitive matching or explicit character groups?


In .net Regex's, there's the possibility to match case-insensitively by doing one of several possible things:

  1. use explicit character groups, for example

    [Ff][Oo][Oo][Bb][Aa][Rr]
    
  2. use case-insensitivity modifier on partial pattern or the full pattern, e.g.

    (?i)foobar
    foo(?i)bar(?-i)
    
  3. turn on case-insensitivity for the Regex via RegexOptions.IgnoreCase

My question is now NOT about functionality or readability (this has been discussed in other questions), but about performance.

Does this make a difference? Is using RegexOptions.IgnoreCase faster than using character groups, and/or is using the inline options faster/slower than the groups or the RegexOptions?

Thx, Tim


Solution

  • Using Regex Hero, I've tested three different expressions described in your question and it brought some insights on each performance test:

    1. [Ff][Oo][Oo][Bb][Aa][Rr]
    2. (?i)foobar
    3. foobar (using RegexOptions.IgnoreCase)

    Below you can find the performance for each case:

    enter image description here

    The test cases returned:

    1. [Ff][Oo][Oo][Bb][Aa][Rr] performed 392,487 iterations per second
    2. (?i)foobar performed 1,174,035 iterations per second (199.1% faster than 1)
    3. foobar (using RegexOptions.IgnoreCase) performed 1,191,317 iterations per second (1.5% faster than 2)