Does string interpolation provide good performance? Here I tested string interpolation with two local variables. I use int.Parse to avoid any possible compiler optimizations.
using System;
using System.Diagnostics;
const int _max = 1000000;
int cats = int.Parse(
"10");
int dogs = int.Parse(
"2");
// Version 1: use string interpolation.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
string result = $
"{cats} cats and {dogs} dogs";
if (result[0] != '1')
{
return;
}
}
s1.Stop();
// Version 2: use string concat.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
string result = cats +
" cats and " + dogs +
" dogs";
if (result[0] != '1')
{
return;
}
}
s2.Stop();
// Version 3: use string format method.
var s3 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
string result = string.Format(
"{0} cats and {1} dogs", cats, dogs);
if (result[0] != '1')
{
return;
}
}
s3.Stop();
Console.WriteLine(s1.Elapsed.TotalMilliseconds);
Console.WriteLine(s2.Elapsed.TotalMilliseconds);
Console.WriteLine(s3.Elapsed.TotalMilliseconds);
66.8248 ms, String interpolation
38.0441 ms, Concat (+)
143.8717 ms, String Format