Performance: string.Create vs FormattableString
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
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
Method | Mean | Error | StdDev | Ratio | Gen 0 | Allocated |
---|---|---|---|---|---|---|
FormattableString | 171.6 ns | 2.32 ns | 2.06 ns | 1.00 | 0.0124 | 208 B |
String.Create | 149.5 ns | 1.15 ns | 1.07 ns | 0.87 | 0.0052 | 88 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.
dotnet add package Meziantou.Analyzer
Do you have a question or a suggestion about this post? Contact me!