C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# program that uses CharEnumerator
using System;
class Program
{
static void Main()
{
// Input string.
string val = "dotnet";
// Get enumerator.
CharEnumerator e = val.GetEnumerator();
// Use in loop.
while (e.MoveNext())
{
char c = e.Current;
Console.WriteLine(c);
}
}
}
Output
d
o
t
n
e
t
Benchmark: This benchmark tests a loop over a short four-character string using the CharEnumerator-style code, and the foreach-style code.
Result: The CharEnumerator method of looping over all the characters in a string is much slower than the foreach method.
Drawback: There is a significant drawback to ever using the CharEnumerator in a loop on a string in the C# language.
C# program that benchmarks CharEnumerator
using System;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method1("test");
}
s1.Stop();
var s2 = Stopwatch.StartNew();
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"));
Console.Read();
}
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;
}
}
Output
33.33 ns CharEnumerator
4.79 ns foreach
Note: CharEnumerator implements those interfaces. But this is not something that will occur in many programs.