Performance: string concatenation vs String.Format vs interpolated string

  • .NET

After writing my previous post about interpolated strings in C#, I was wondering what is the most performant way to concatenate strings. So, I use BenchmarkDotnet to quickly get the result.

Here's the code of the benchmark:

// Full code: https://gist.github.com/meziantou/b120126088457f5f87ad200f4f7bf6b0
class Program
{
    static void Main(string[] args)
    {
        BenchmarkRunner.Run<StringBenchmark>();
    }
}

[OrderProvider(SummaryOrderPolicy.FastestToSlowest)]
[CoreJob]
[MemoryDiagnoser]
class StringBenchmark
{
    [Benchmark]
    public string StringConcatenation1() => "test" + 0 + "test0";

    [Benchmark]
    public string StringFormat1() => string.Format("test{0}{1}", 0, "test0");

    [Benchmark]
    public string StringInterpolation1() => $"test{0}{"test0"}"; // Should be the same as StringFormat

    [Benchmark]
    public string FormattableString1() => Format($"test{0}{"test0"}"); // Force the creation of a FormattableString

    // ...
    // same tests with 5, 10, 20, 50 100 arguments

    private static string Format(FormattableString fs) => fs.ToString();
}
MethodMeanErrorStdDevGen 0Allocated
StringConcatenation182.39 ns1.732 ns1.8534 ns0.0330104 B
StringFormat1176.44 ns1.034 ns0.9674 ns0.0329104 B
StringInterpolation1177.31 ns1.157 ns1.0824 ns0.0329104 B
FormattableString1229.26 ns4.654 ns6.9661 ns0.0558176 B
StringConcatenation5453.13 ns2.980 ns2.4887 ns0.1903600 B
FormattableString5661.04 ns17.338 ns23.1458 ns0.1621512 B
StringFormat5688.18 ns7.096 ns6.2907 ns0.1516480 B
StringInterpolation5692.05 ns3.329 ns2.9508 ns0.1516480 B
StringConcatenation10899.42 ns15.189 ns13.4643 ns0.35001104 B
FormattableString101,160.01 ns9.950 ns8.3090 ns0.2956936 B
StringInterpolation101,317.73 ns9.445 ns8.3726 ns0.2861904 B
StringFormat101,330.47 ns9.240 ns8.6433 ns0.2861904 B
StringConcatenation201,794.73 ns7.335 ns6.1252 ns0.68092144 B
FormattableString202,260.88 ns22.249 ns18.5790 ns0.90032840 B
StringInterpolation202,625.90 ns2.727 ns1.9720 ns0.88882808 B
StringFormat202,642.51 ns20.843 ns18.4764 ns0.88882808 B
StringConcatenation504,394.86 ns86.688 ns106.4604 ns1.67085264 B
FormattableString505,427.57 ns35.227 ns32.9509 ns2.19736920 B
StringFormat506,313.41 ns32.824 ns27.4097 ns2.18206888 B
StringInterpolation506,358.77 ns50.488 ns42.1595 ns2.18206888 B
StringConcatenation1009,011.67 ns62.487 ns58.4504 ns3.311210464 B
FormattableString10010,941.37 ns88.319 ns78.2928 ns4.409813920 B
StringFormat10012,721.01 ns49.627 ns41.4407 ns4.409813888 B
StringInterpolation10012,924.46 ns329.898 ns392.7199 ns4.409813888 B

The 4 methods are almost equivalents. But, you can notice that string concatenation is a little faster for a very small number of arguments.

Follow me:
Enjoy this blog?Buy Me A CoffeeDonate with PayPal

Comments

Simon Mourier -

You definitely convinced me of the absence of benefit of string interpolation 😃

Leave a reply