I've been doing some code refactoring in my C# projects. I got a Resharper code analysis warning:
"Redundant string interpolation"
This happens in following scenario:
void someFunction(string param)
{
...
}
someFunction($"some string");
I've read string interpolation is rewritten to string.Format
at compile time. Then I tried following:
someFunction(string.Format("some string"));
This time I get:
Redundant string.Format call.
My question is: Except the code cleanness, is the run-time performance affected by these redundant calls or the performance is the same for:
someFunction($"some string")
someFunction("some string")
someFunction(string.Format("some string"))
Well, let's perform a benchmark:
private static long someFunction(string value) {
return value.Length;
}
...
Stopwatch sw = new Stopwatch();
int n = 100_000_000;
long sum = 0;
sw.Start();
for (int i = 0; i < n; ++i) {
// sum += someFunction("some string");
// sum += someFunction($"some string");
sum += someFunction(string.Format("some string"));
}
sw.Stop();
Console.Write(sw.ElapsedMilliseconds);
Outcome (.Net 4.8 IA-64 Release), average results:
224 // "some string"
225 // $"some string"
8900 // string.Format("some string")
So we can see, that compiler removes unwanted $
but executes string.Format
which wastes time to understand that we don't have any formatting