You can loop through strings with foreach and for-loops. I wondered if the CharEnumerator version of the string loop had any advantage over these methods.
using System;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
var s1 = Stopwatch.StartNew();
// Version 1: use CharEnumerator.
for (int i = 0; i < _max; i++)
{
Method1(
"test");
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use foreach-loop.
for (int i = 0; i < _max; i++)
{
Method2(
"test");
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString(
"0.00 ns"));
}
static int Method1(string val)
{
int res = 0;
CharEnumerator c = val.GetEnumerator();
while (c.MoveNext())
{
res += (int)c.Current;
}
return res;
}
static int Method2(string val)
{
int res = 0;
foreach (char c in val)
{
res += (int)c;
}
return res;
}
}
33.33 ns CharEnumerator
4.79 ns foreach