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;
}
I’m particularly concerned about the Item accessor on the string. Not sure if it is just pointer arithmetic like C/C++.
I tested these implementations
Here are my timing results for 100000 iterations on a string of ~25k. Lower is faster.
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+)