3주 전 · Jul 30, 2026 3:45 PM
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!