In order to produce a formatted string, both `string.Create` and either `FormattableString.Invariant` or `FormattableString.CurrentCulture` can be used. However, `string.Create` rents array buffers from `ArrayPool<char>` making it more performant, as well as preventing unnecessary allocations and future stress on the Garbage Collector.
We measured a significant improvement both in execution time and memory allocation. For more details see the `Benchmarks` section from the `More info` tab.
== How to fix it
Replace calls to `FormattableString.CurrentCulture` or `FormattableString.Invariant` with calls to `string.Create(CultureInfo.CurrentCulture, ...)` or `string.Create(CultureInfo.InvariantCulture, ...)` respectively.
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated#compilation-of-interpolated-strings[Compilation of interpolated strings]
=== Benchmarks
The results were generated by running the following snippet with https://github.com/dotnet/BenchmarkDotNet[BenchmarkDotNet]:
[options="header"]
|===
| Method | Runtime | Mean | StdDev | Allocated
| StringCreate | .NET 7.0 | 152.5 ms | 3.09 ms | 83.92 MB
| FormattableString | .NET 7.0 | 191.8 ms | 6.92 ms | 198.36 MB
|===
[source,csharp]
----
int Value = 42;
DateTime Now = DateTime.UtcNow;
[Params(1_000_000)]
public int N;
[Benchmark]
public void StringCreate()
{
for (int i = 0; i < N; i++)
{
_ = string.Create(CultureInfo.InvariantCulture, $"{Now}: Value is {Value}");
}
}
[Benchmark]
public void FormattableStringInvariant()
{
for (int i = 0; i < N; i++)
{
_ = FormattableString.Invariant($"{Now}: Value is {Value}");