gpt4 book ai didi

c# - 计算大型 .NET 字符串中换行符的最快方法是什么?

转载 作者:可可西里 更新时间:2023-11-01 07:51:26 26 4
gpt4 key购买 nike

有没有办法改善这个:

private static int CountNewlines(string s)
{
int len = s.Length;
int c = 0;
for (int i=0; i < len; i++)
{
if (s[i] == '\n') c++;
}
return c;
}

我特别关心字符串上的 Item 访问器。不确定它是否只是像 C/C++ 那样的指针运算。

最佳答案

我测试了这些实现

private static int Count1(string s)
{
int len = s.Length;
int c = 0;
for (int i=0; i < len; i++)
{
if (s[i] == '\n') c++;
}
return c+1;
}

private static int Count2(string s)
{
int count = -1;
int index = -1;

do
{
count++;
index = s.IndexOf('\n', index + 1);
}
while (index != -1);

return count+1;
}

private static int Count3(string s)
{
return s.Count( c => c == '\n' ) + 1;
}


private static int Count4(string s)
{
int n = 0;
foreach( var c in s )
{
if ( c == '\n' ) n++;
}
return n+1;
}

private static int Count5(string s)
{
var a = s.ToCharArray();
int c = 0;
for (int i=0; i < a.Length; i++)
{
if (a[i]=='\n') c++;
}
return c+1;
}

这是我对 ~25k 的字符串进行 100000 次迭代的计时结果。越低越快。

              Time  Factor
Count1 4.8581503 1.4
Count2 4.1406059 1.2
Count3 45.3614124 13.4
Count4 3.3896130 1.0
Count5 5.9304543 1.7

令我惊讶的是,Enumerator 实现对我来说是最快的,速度非常快 - 比下一个最接近的实现快 20%。无论方法运行的顺序如何,结果都是可重复的。我还使用了预热阶段来确保 transient 效应(jit 等)被排除在外。

这是用于发布构建 (/optimize+)

关于c# - 计算大型 .NET 字符串中换行符的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2557002/

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