To check the performance advantage, I created a benchmark. I timed the cost of lowercasing the string "Test" one million times and took the average.
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
static string Lowercase1(string value)
{
return value.ToLower();
}
static Dictionary<string, string> _lowercase = new Dictionary<string, string>();
static string Lowercase2(string value)
{
string lookup;
if (_lowercase.TryGetValue(value, out lookup))
{
return lookup;
}
lookup = value.ToLower();
_lowercase[value] = lookup;
return lookup;
}
const int _max = 1000000;
static void Main()
{
// Version 1: use ToLower.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (Lowercase1(
"TEST") !=
"test")
{
return;
}
}
s1.Stop();
// Version 2: use ToLower with caching.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (Lowercase2(
"TEST") !=
"test")
{
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"));
}
}
99.54 ns Lowercase1
31.09 ns Lowercase2