I've compared your favorite with seven alternatives:
static long LinesCount(string s)
{
long count = 0;
int position = 0;
while ((position = s.IndexOf('\n', position)) != -1)
{
count++;
position++;
}
return count;
}
static long LinesCount2(string s)
{
long count = 0;
int posMax = s.Length;
for (int position = 0; position < posMax; )
if (s[position++] == '\n')
count++;
return count;
}
static long LinesCount3(string s)
{
long count = 0;
int posMax = s.Length;
char[] a = s.ToCharArray();
for (int position = 0; position < posMax; )
if (a[position++] == '\n')
count++;
return count;
}
static long LinesCount4(string s)
{
long count = 0;
int position = -1;
while ((position = s.IndexOf('\n', position + 1)) != -1)
{
count++;
}
return count;
}
static long LinesCount5(string s)
{
long count = 0;
int posMax = s.Length;
char[] a = s.ToCharArray();
foreach (char c in a)
if (c == '\n')
count++;
return count;
}
static long LinesCount6(string s)
{
long count = 0;
foreach (char c in s)
if (c == '\n')
count++;
return count;
}
static long LinesCount7(string s)
{
return s.Length - s.Replace("\n", "").Length;
}
static long LinesCount8(string s)
{
return s.Split('\n').Length - 1;
}
The fastest was LinesCount4()
which is a slight variation of your original. I've just reduced the loop by one variable assignment. Some of the other contenders look nice. Others eat up a lot of memory. LinesCount6()
is probably a good compromise between speed and style.
Greetings!