Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant string interpolation and performance

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"))
like image 834
EylM Avatar asked Jul 30 '19 13:07

EylM


2 Answers

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.

like image 85
Kris Vandermotten Avatar answered Sep 20 '22 12:09

Kris Vandermotten


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

like image 44
Dmitry Bychenko Avatar answered Sep 19 '22 12:09

Dmitry Bychenko