What is the fastest way to uppercase the first letter in a string? We compare the 2 versions of UppercaseFirst in a benchmark program.
using System;
using System.Diagnostics;
class Program
{
static string UppercaseFirst(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
return char.ToUpper(s[0]) + s.Substring(1);
}
static string UppercaseFirst2(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
const int _max = 1000000;
static void Main()
{
var s1 = Stopwatch.StartNew();
// Version 1: test first method.
for (int i = 0; i < _max; i++)
{
if (UppercaseFirst(
"denver") !=
"Denver")
{
return;
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: test second method.
for (int i = 0; i < _max; i++)
{
if (UppercaseFirst2(
"denver") !=
"Denver")
{
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"));
}
}
60.66 ns UppercaseFirst
42.66 ns UppercaseFirst2