Redundant string interpolation and performance
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
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.