String Interpolation vs String.Format

C#StringPerformanceResharperString Interpolation

C# Problem Overview


Is there a noticable performance difference between using string interpolation:

myString += $"{x:x2}";

vs String.Format()?

myString += String.Format("{0:x2}", x);

I am only asking because Resharper is prompting the fix, and I have been fooled before.

C# Solutions


Solution 1 - C#

Noticable is relative. However: string interpolation is turned into string.Format() at compile-time so they should end up with the same result.

There are subtle differences though: as we can tell from this question, string concatenation in the format specifier results in an additional string.Concat() call.

Solution 2 - C#

The answer is both yes and no. ReSharper is fooling you by not showing a third variant, which is also the most performant. The two listed variants produce equal IL code, but the following will indeed give a boost:

myString += $"{x.ToString("x2")}";

Full test code

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Diagnostics.Windows;
using BenchmarkDotNet.Running;

namespace StringFormatPerformanceTest
{
    [Config(typeof(Config))]
    public class StringTests
    {
        private class Config : ManualConfig
        {
            public Config() => AddDiagnoser(MemoryDiagnoser.Default, new EtwProfiler());
        }

        [Params(42, 1337)]
        public int Data;

        [Benchmark] public string Format() => string.Format("{0:x2}", Data);
        [Benchmark] public string Interpolate() => $"{Data:x2}";
        [Benchmark] public string InterpolateExplicit() => $"{Data.ToString("x2")}";
    }

    class Program
    {
        static void Main(string[] args)
        {
            var summary = BenchmarkRunner.Run<StringTests>();
        }
    }
}

Test results

|              Method | Data |      Mean |  Gen 0 | Allocated |
|-------------------- |----- |----------:|-------:|----------:|
|              Format |   42 | 118.03 ns | 0.0178 |      56 B |
|         Interpolate |   42 | 118.36 ns | 0.0178 |      56 B |
| InterpolateExplicit |   42 |  37.01 ns | 0.0102 |      32 B |
|              Format | 1337 | 117.46 ns | 0.0176 |      56 B |
|         Interpolate | 1337 | 113.86 ns | 0.0178 |      56 B |
| InterpolateExplicit | 1337 |  38.73 ns | 0.0102 |      32 B |

The InterpolateExplicit() method is faster since we now explicitly tell the compiler to use a string. No need to box the object to be formatted. Boxing is indeed very costly. Also, note that we reduced the allocations a bit.

Solution 3 - C#

string interpolation is turned into string.Format() at compile-time.

Also in string.Format you can specify several outputs for single argument, and different output formats for single argument. But string interpolation is more readable I guess. So, it's up to you.

a = string.Format("Due date is {0:M/d/yy} at {0:h:mm}", someComplexObject.someObject.someProperty);

b = $"Due date is {someComplexObject.someObject.someProperty:M/d/yy} at {someComplexObject.someObject.someProperty:h:mm}";

There is some performance test results https://koukia.ca/string-interpolation-vs-string-format-string-concat-and-string-builder-performance-benchmarks-c1dad38032a

Solution 4 - C#

The question was about performance, however the title just says "vs", so I feel like have to add a few more points, some of them are opinionated though.

  • Localization

    • String interpolation cannot be localized due to it's inline code nature. Before localization it has be turned into string.Format. However, there is tooling for that (e.g. ReSharper).
  • Maintainability (my opinion)

    • string.Format is far more readable, as it focuses on the sentence what I'd like to phrase, for example when constructing a nice and meaningful error message. Using the {N} placeholders give me more flexibility and it's easier to modify it later.
    • Also, the inlined format specifier in interploation is easy to misread, and easy to delete together with the expression during a change.
    • When using complex and long expressions, interpolation quickly gets even more hard to read and maintain, so in this sense it doesn't scale well when code is evolving and gets more complex. string.Format is much less prone to this.
    • At the end of the day it's all about separation of concerns: I don't like to mix the how it should present with the what should be presented.

So based on these I decided to stick with string.Format in most of my code. However, I've prepared an extension method to have a more fluent way of coding which I like much more. The extension's implementaiton is a one-liner, and it looks simply like this in use.

var myErrorMessage = "Value must be less than {0:0.00} for field {1}".FormatWith(maximum, fieldName);

Interpolation is a great feature, don't get me wrong. But IMO it shines the best in those languages which miss the string.Format-like feature, for example JavaScript.

Solution 5 - C#

You should note that there have been significant optimizations on String Interpolation in C#10 and .NET 6 - String Interpolation in C# 10 and .NET 6.

I've been migrating all of my usage of not only string formatting, but also my usage of string concatenation, to use String Interpolation.

I'd be just as concerned, if not more, with memory allocation differences between the different methods. I've found that String Interpolation almost always wins for both speed and memory allocation when working with a smallish number of strings. If you have an undetermined (not known at design-time) number of strings, you should always use System.Text.StringBuilder.Append(xxx) or System.Text.StringBuilder.AppendFormat(xxx)

Also, I'd callout your usage of += for string concatenation. Be very careful and only do so for a small number of small strings.

Solution 6 - C#

Maybe to late to mention but didnt found others mentioned it: I noticed the += operator in your question. Looks like you are creating some hex output of something executing this operation in cycle.

Using concat on strings (+=) especially in cycles may result in hardly foundable problem: an OutOfMemoryException while analysing the dump will show tons of free memory inside!

What happens?

  1. The memory management will look for a continous space enough for the result string.
  2. The concatenated string written there.
  3. The space used for storing value for original left hand side variable freed.

Note that the space allocated in step #1 is certainly bigger than the space freed in step #3.

In the next cycle the same happens and so on. How our memory will look like assuming 10 bytes long string was added in each cycle to an originally 20 bytes long string 3 times?

[20 bytes free]X1[30 bytes free]X2[40 bytes free]X2[50 bytes allocated]

(Because almost sure there are other commands using memory during the cycle I placed the Xn-s to demonstrate their memory allocations. These may be freed or still allocated, follow me.)

If at the next allocation MM founds no enough big continous memory (60 bytes) then it tries to get it from OS or by restructuring free spaces in its outlet. The X1 and X2 will be moved somewhere (if possible) and a 20+30+40 continous block become available. Time taking but available.

BUT if the block sizes reach 88kb (google for it why 88kb) they will be allocated on Large Object Heap. Free blocks here wont be compacted anymore.

So if your string += operation results are going past this size (e.g. you are building a CSV file or rendering something in memory this way) the above cycle will result in chunks of free memory of continously growing sizes, the sum of them can be gigabytes, but your app will terminate with OOM because it wont be able to allocate a block of maybe as small as 1Mb because none of the chunks are big enough for it :)

Sorry for long explanation but it happened some years ago and it was a hard lession. I am fighting against unappropriate use of string concats since then.

Solution 7 - C#

There is an important note about String.Format in microsoft's site: https://docs.microsoft.com/en-us/dotnet/api/system.string.format?view=net-6.0

"Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. An interpolated string is a string that contains interpolated expressions. Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. "

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKrythicView Question on Stackoverflow
Solution 1 - C#Jeroen VannevelView Answer on Stackoverflow
Solution 2 - C#l33tView Answer on Stackoverflow
Solution 3 - C#PaulView Answer on Stackoverflow
Solution 4 - C#Zoltán TamásiView Answer on Stackoverflow
Solution 5 - C#Dave BlackView Answer on Stackoverflow
Solution 6 - C#clyView Answer on Stackoverflow
Solution 7 - C#ozan.yarciView Answer on Stackoverflow