Performance: string.Create vs FormattableString

 
 
  • Gérald Barré

Interpolated strings are very common in C#. For instance, you can write $"Hello {name}! You are {age} years old.". This expression is evaluated using the current culture. If you want to use an invariant culture, you can use FormattableString.Invariant($"..."). Starting with .NET 6 and C# 10, you can use string.Create(culture, $"...") to evaluate the interpolated string using a specific culture, including the invariant culture.

This new method is faster and allocates less than the FormattableString.Invariant thanks to the new interpolated string handlers feature introduced with .NET 6.

#Benchmark

C#
using System.Globalization;
using BenchmarkDotNet.Attributes;

namespace Benchmark;

[MemoryDiagnoser]
[ReturnValueValidator]
public class StringCreateBenchmark
{
    int a = 1;
    DateTime b = DateTime.UtcNow;

    [Benchmark]
    public string StringCreate()
    {
        return string.Create(CultureInfo.InvariantCulture, $"text {a} test {b}");
    }

    [Benchmark]
    public string FormattableStringInvariant()
    {
        return FormattableString.Invariant($"text {a} test {b}");
    }
}
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22622
AMD Ryzen 7 5800X, 1 CPU, 16 logical and 8 physical cores
.NET SDK=7.0.100-preview.7.22377.5
  [Host]     : .NET 7.0.0 (7.0.22.37506), X64 RyuJIT
  DefaultJob : .NET 7.0.0 (7.0.22.37506), X64 RyuJIT
MethodMeanErrorStdDevRatioGen 0Allocated
FormattableString171.6 ns2.32 ns2.06 ns1.000.0124208 B
String.Create149.5 ns1.15 ns1.07 ns0.870.005288 B

#Use a Roslyn Analyzer to update your code

You can use Meziantou.Analyzer to find and update the code that can benefit from the string.Create method.

C#
dotnet add package Meziantou.Analyzer

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub