gpt4 book ai didi

c# - string.IndexOf OrdinalIgnoreCase 与 CurrentCultureIgnoreCase 的性能

转载 作者:可可西里 更新时间:2023-11-01 03:10:47 28 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
String comparison in dotnet framework 4

我注意到我机器上的一个 UI 应用程序存在性能问题,该应用程序正在执行大量字符串比较以过滤大型列表。我将问题追溯到在对 string.IndexOf 的调用中使用 OrdinalIgnoreCase。以下基准测试是在没有附加调试器的情况下在 Release 中运行的,它是一个在 VS 2010、Windows 7 中构建的 4.0 项目,我在这台机器上安装了 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);
}

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com