
How efficient is the Replace method with various arguments in your C# programs? The time required for the string Replace method varies depending on what arguments are used and whether anything is replaced.
This program tests four calls to the Replace method. The first two calls use char arguments. The second two calls use string arguments. Only the second and the fourth calls actually require that the string be changed in memory.
This C# example program shows one way to optimize Replace performance.
Program that benchmarks Replace [C#]
using System;
using System.Diagnostics;
class Program
{
const int _max = 1000000;
static void Main()
{
string test = "dotnetperls";
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
string t = test.Replace('x', 'y');
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
string t = test.Replace('d', 'y');
}
s2.Stop();
var s3 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
string t = test.Replace("x", "y");
}
s3.Stop();
var s4 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
string t = test.Replace("d", "y");
}
s4.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.WriteLine(((double)(s3.Elapsed.TotalMilliseconds * 1000 * 1000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s4.Elapsed.TotalMilliseconds * 1000 * 1000) /
_max).ToString("0.00 ns"));
Console.Read();
}
}
Output
13.00 ns
47.75 ns
73.26 ns
117.07 ns
Results. The first call to Replace, which has no effect on the string and uses char arguments, was very fast. The second call was slower because it actually required the string be changed. The third and fourth calls, which used string arguments, were much slower.
Calls to Replace that do not require the string data to be changed are considerably faster than calls that actually change the string. The version of Replace that uses char arguments is much faster than the version that uses string arguments. Prefer the char version when possible.
String Type