Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Tutorial

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

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rozpustnik: 103
Data dołączenia: Apr 2018
Posty: 40
Dzięki: 24
3 tygodnie temu · 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
Rozpustnik: 146
Data dołączenia: Aug 2019
Posty: 33
Dzięki: 31
3 tygodnie temu · 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
Rozpustnik: 57
Data dołączenia: Mar 2019
Posty: 18
Dzięki: 40
3 tygodnie temu · Jul 31, 2026 9:40 AM
#3

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