String Interpolation performs better than string. Format?

Asked

Viewed 455 times

10

I use Resharper and a few days ago I started using some C# 6 features.

In various parts of the code use string.Format() and I realized that Resharper suggests that these snippets be replaced by string Interpolation.

The question is, why does Resharper suggest this exchange?

String Interpolation has a better performance than string.Format() or this suggestion is only to make the code more readable?

2 answers

9


The best way to find out is by testing. I did a simple test:

using static System.Console;
using System.Diagnostics;
                    
public class Program {
    public static void Main() {
        var x = "";
        var sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < 10000; i++) x = string.Format("teste de string formatada com resultado: {0}", i + 5);
        sw.Stop();
        WriteLine(sw.ElapsedTicks);
        sw.Restart();
        for (var i = 0; i < 10000; i++) x = $"teste de string formatada com resultado: {i + 5}";
        sw.Stop();
        WriteLine(sw.ElapsedTicks);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

The best test will be done in a controlled environment and not on a shared server where you don’t know what is running. I’ve run it a few times. And overall the result was almost the same.

But it is important to note that in other patterns this result may be different. This kind of test only says about this particular situation, but it can generalize. It may be that mounting the test otherwise gives a different result, even if it performs the same thing. To properly test it is necessary to deeply understand the implementations to try to find the points where each one stands out and where they fail. If the implementation changes, the test no longer serves.

I put in the Sharplab to see the generated code and both use the Format().

More information on documentation. As it is not in the documentation is implementation detail and one day can change.

The great advantage is not in speed, but in simplification and convenience. And Resharper suggests because it is more elegant, not because it is faster.

In C# 10, or another if you are late, you will have the string constant interpolated that will bring a difference in performance. See more.

9

There is no difference. The compiler will call string.Format() whenever you use the notation $.

In other words, the generated IL will be the same. Therefore, there is no difference in performance.

Source: https://roslyn.codeplex.com/discussions/570614

Browser other questions tagged

You are not signed in. Login or sign up in order to post.