什么是计算在一个大的.NET字符串换行的最快的方法是什么? [英] What is the fastest way to count newlines in a large .NET string?

查看:108
本文介绍了什么是计算在一个大的.NET字符串换行的最快的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法来改善这样的:

Is there a way to improve this:

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;
}

我特别担心的字符串项访问。不知道这是否只是指针运算,如C / C ++。

I'm particularly concerned about the Item accessor on the string. Not sure if it is just pointer arithmetic like 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;
}

下面是我的计时结果为100000迭代上〜25K的字符串。较低的速度更快。

Here are my timing results for 100000 iterations on a string of ~25k. Lower is faster.

              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

奇怪的是,对我来说,枚举器实现了最快的对我来说,一个显著度 - 比最接近的执行速度快20%。结果是可重复的,而与该方法运行的顺序的。我也用一个热身阶段,以确保瞬态效应(JIT等)被提取出来。

Surprisingly, to me, the Enumerator implementation was fastest for me, by a significant degree - 20% faster than the next closest implementation. The results were repeatable, regardless of the order in which the methods were run. I also used a warmup phase to insure transient effects (jit, etc) were factored out.

这是一个发布版本(/优化+)

This was for a release build (/optimize+)

这篇关于什么是计算在一个大的.NET字符串换行的最快的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆