Developer knowledge network · moderated exchange

Супольнасць UnreliableCode

Супольнасць распрацоўшчыкаў даследаванняў, зваротнага праектавання і кадавання

Knowledge indexжыць
4Categories
919Threads
2.8KПаведамленні
Tutorial

Zero-Allocation String Formatting in C# using string.Create and ISpanFormattable [StackOverflow Architecture Guide]

dotnet_runtime_architect
.NET Core Specialist
MEMBER
прадстаўнік: 103
Дата далучэння: Apr 2018
Паведамленні: 40
Дзякуй: 24
3 тыдняў таму · Jul 30, 2026 3:45 PM
#1

How string.Create allocates the exact string buffer length without intermediate string concatenations:

CSHARP
public static string FormatOrderCode(int orderId, int regionCode)
{
    // Allocates exactly 10 characters with 0 intermediate StringBuilder or string allocations!
    return string.Create(10, (orderId, regionCode), static (span, state) =>
    {
        span[0] = 'O';
        span[1] = 'R';
        span[2] = 'D';
        span[3] = '-';
        state.regionCode.TryFormat(span.Slice(4, 2), out _, "D2");
        span[6] = '-';
        state.orderId.TryFormat(span.Slice(7, 3), out _, "D3");
    });
}

Passing a static lambda ensures zero closure state allocations on the heap!

profiler_pat
Performance Hunter
MEMBER
прадстаўнік: 146
Дата далучэння: Aug 2019
Паведамленні: 33
Дзякуй: 31
3 тыдняў таму · Jul 30, 2026 8:50 PM
#2

string.Create is how the .NET BCL implements fast string formatting internally. Extremely clean.

csharp_async_master
Async & Task Expert
MEMBER
прадстаўнік: 57
Дата далучэння: Mar 2019
Паведамленні: 18
Дзякуй: 40
3 тыдняў таму · Jul 31, 2026 9:40 AM
#3

Combining with ISpanFormattable.TryFormat completely eliminates StringBuilder allocations in high-volume logging.