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"))
As the author of that specific optimization in the C# compiler, I can confirm that $"some string"
is optimized to "some string"
by the C# compiler. That's a constant, and so virtually no code needs to execute at runtime to calculate it.
On the other hand, string.Format("some string")
is a method invocation, and the method has to be invoked at runtime. Obviously, there is a cost associated with that call. It won't do anything useful of course, hence the warning "Redundant string.Format call."
Update: in fact, interpolations without fill-ins have always been optimized to the resulting string by the compiler. All it does is unescape {{
to {
and }}
to }
. My change was to optimize interpolations where all fill-ins are strings without formatting to string concatenations.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With