String interpolation has a better performance than string.Format?

10

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

In several parts of the code I use string.Format() and I noticed that the Resharper suggests that these snippets be replaced by string interpolation .

The question is: why does the Resharper suggest this exchange?

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

    
asked by anonymous 19.10.2015 / 14:27

2 answers

9

There is no difference at all. 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 performance difference.

Source: link

    
19.10.2015 / 19:14
8

The best way to find out is to test. 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);
    }
}

See running on dotNetFiddle .

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

But it is important to note that in other standards this result may be different. This type of test only says about this specific situation, but it can be generalized. It may be that assembling the test otherwise gives a different result, even if it does the same thing. To properly test it is necessary to deeply understand the implementations to try to find the points where each stands out and fail. If the implementation changes, the test is no longer useful.

The big advantage is not speed, but simplicity and convenience.

    
19.10.2015 / 14:46