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.