Replace can be optimized. Suppose in our program many string replacements must be done. But often nothing is changed in actual strings.
using System;
using System.Diagnostics;
class Program
{
static string ReplaceAll(string text)
{
text = text.Replace(
"<span>Cat ",
"<span>Cats ");
text = text.Replace(
"<span>Clear ",
"<span>Clears ");
text = text.Replace(
"<span>Dog ",
"<span>Dogs ");
text = text.Replace(
"<span>Draw ",
"<span>Draws ");
return text;
}
static string ReplaceAllWithContains(string text)
{
if (text.Contains(
"<span>C"))
{
text = text.Replace(
"<span>Cat ",
"<span>Cats ");
text = text.Replace(
"<span>Clear ",
"<span>Clears ");
}
if (text.Contains(
"<span>D"))
{
text = text.Replace(
"<span>Dog ",
"<span>Dogs ");
text = text.Replace(
"<span>Draw ",
"<span>Draws ");
}
return text;
}
const int _max = 1000000;
static void Main()
{
Console.WriteLine(ReplaceAll(
"<span>Dog 100</span>"));
Console.WriteLine(ReplaceAllWithContains(
"<span>Dog 100</span>"));
var s1 = Stopwatch.StartNew();
// Version 1: use Replace.
for (int i = 0; i < _max; i++)
{
string result = ReplaceAll(
"<span>Dog 100</span>");
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use Contains and Replace.
for (int i = 0; i < _max; i++)
{
string result = ReplaceAllWithContains(
"<span>Dog 100</span>");
}
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"));
}
}
<span>Dogs 100</span>
<span>Dogs 100</span>
128.76 ns ReplaceAll
98.89 ns ReplaceAllWithContains