What is the fastest way to count newlines in a large .NET string?

前端 未结 6 1963
闹比i
闹比i 2021-02-13 04:18

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++)
    {
           


        
6条回答
  •  半阙折子戏
    2021-02-13 04:54

    Well, String implements IEnumerable, so I'd definitely try:

    s.Count( c => c == '\n' )
    

    As nice as this looks, the original method is 30x faster :)

    I haven't given up on the IEnumerable yet, so I've also tried:

    int n = 0;
    foreach( var c in s )
    {
        if ( c == '\n' ) n++;
    }
    return n;
    

    which seems as fast as the original method.

提交回复
热议问题