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.