.net Regex 性能考虑:使用(部分或全局)不区分大小写的匹配或显式字符组?

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

在 .net Regex 中,可以通过以下几种可能的方式之一进行不区分大小写的匹配:

  1. 使用明确的字符组,例如

    [Ff][Oo][Oo][Bb][Aa][Rr]
    
  2. 对部分模式或完整模式使用不区分大小写的修饰符,例如

    (?i)foobar
    foo(?i)bar(?-i)
    
  3. 通过RegexOptions.IgnoreCase

  4. 为正则表达式打开不区分大小写

我现在的问题不是关于功能或可读性(这已在其他问题中讨论过),而是关于性能。

这有什么不同吗?使用 RegexOptions.IgnoreCase 比使用字符组快,and/or 使用内联选项 faster/slower 比组或 RegexOptions?

谢谢, 蒂姆

我使用 Regex Hero 测试了您问题中描述的三种不同的表达式,它为每个性能测试带来了一些见解:

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

您可以在下面找到每个案例的表现:

返回的测试用例:

  1. [Ff][Oo][Oo][Bb][Aa][Rr] 每秒执行 392,487 次迭代
  2. (?i)foobar 每秒执行 1,174,035 次迭代(199.1% 比 1 快)
  3. foobar(使用 RegexOptions.IgnoreCase)每秒执行 1,191,317 次迭代(1.5% 比 2 快)