Developer knowledge network · moderated exchange

UnreliableCode コミュニティ

開発者リサーチ、リバース エンジニアリング、コーディング コミュニティ

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.