string.IndexOf OrdinalIgnoreCase与CurrentCultureIgnoreCase的性能

时间:2012-03-16 01:28:18

标签: c# string performance

  

可能重复:
  String comparison in dotnet framework 4

我注意到我的计算机在UI应用程序中出现性能问题,该应用程序正在进行大量字符串比较以对大型列表进行过滤。我在调用string.IndexOf时跟踪问题直到使用OrdinalIgnoreCase。以下基准测试是在未附带调试器的Release中运行的,它是在VS 2010中构建的4.0项目,Windows 7,我确实在这台机器上安装了4.5 beta,我不确定这是否会影响这一点。

1.190 seconds for OrdinalIgnoreCase
0.178 seconds for CurrentCultureIgnoreCase
0.175 seconds for InvariantCultureIgnoreCase

0.101 seconds for Ordinal
0.132 seconds for CurrentCulture
0.126 seconds for InvariantCulture

1.176 seconds for OrdinalIgnoreCase
0.189 seconds for CurrentCultureIgnoreCase
0.183 seconds for InvariantCultureIgnoreCase

0.104 seconds for Ordinal
0.138 seconds for CurrentCulture
0.127 seconds for InvariantCulture

正如您所看到的,OrdinalIgnoreCase慢了6.5倍!但没有IgnoreCase Ordinal是最快的。在multiple places microsoft recommends OrdinalIgnoreCase中获得最佳性能。任何人都可以复制这些结果或解释为什么OrdinalIgnoreCase在这个测试中变得如此之慢?

private static void Test(string search, string key, StringComparison comparison, int trials)
{
    var sw = Stopwatch.StartNew();

    for (int i = 0; i < trials; i++)
    {
        search.IndexOf(key, comparison);
    }

    Console.WriteLine("{0:0.000} seconds for {1}", sw.ElapsedMilliseconds / 1000.0, comparison);
}


static void Main(string[] args)
{
    int trials = 1000000;
    var search = Guid.NewGuid().ToString("N");
    var key = "34";

    Test(search, key, StringComparison.OrdinalIgnoreCase, trials);
    Test(search, key, StringComparison.CurrentCultureIgnoreCase, trials);
    Test(search, key, StringComparison.InvariantCultureIgnoreCase, trials);
    Test(search, key, StringComparison.Ordinal, trials);
    Test(search, key, StringComparison.CurrentCulture, trials);
    Test(search, key, StringComparison.InvariantCulture, trials);

    Test(search, key, StringComparison.OrdinalIgnoreCase, trials);
    Test(search, key, StringComparison.CurrentCultureIgnoreCase, trials);
    Test(search, key, StringComparison.InvariantCultureIgnoreCase, trials);
    Test(search, key, StringComparison.Ordinal, trials);
    Test(search, key, StringComparison.CurrentCulture, trials);
    Test(search, key, StringComparison.InvariantCulture, trials);
}

1 个答案:

答案 0 :(得分:9)

这显然是.net 4中已知的性能问题,我发现this bug entry on connect.microsoft.com

并且有回复

  

微软发表于2012年2月2日上午11:43我们能够重现   这个问题。问题已经解决,修复将在   下一个版本。谢谢你的反馈。

我不确定下一个版本是什么,我只想选择使用InvariantCultureIgnoreCase