Here we consider 2 loops over a string literal's character data. Each loop compares each character in the source string against the space character.
using System;
using System.Diagnostics;
class Program
{
static int A(string input)
{
int spaces = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '
')
{
spaces++;
}
}
return spaces;
}
static int B(string input)
{
int spaces = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i].ToString() ==
" ")
{
spaces++;
}
}
return spaces;
}
const int _max = 1000000;
static void Main()
{
var s1 = Stopwatch.StartNew();
// Version 1: use direct char for-loop.
for (int i = 0; i < _max; i++)
{
if (A(
"Dot Net Perls website") == 0)
{
return;
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use ToString in for-loop.
for (int i = 0; i < _max; i++)
{
if (B(
"Dot Net Perls website") == 0)
{
return;
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
}
24.32 ns A
264.23 ns B (ToString)