← All articles

Optimizing .NET: Day 3

From December 1 through Christmas Eve, I’ll cover one .NET runtime-library optimization a day.

decimal.TryFormat()#

C#
using System.Globalization;

Span<char> chars = stackalloc char[32];
12345.6700m.TryFormat(chars, out int charsWritten, provider: CultureInfo.InvariantCulture);
// chars[..charsWritten] contains "12345.6700".

Without the patch, decimal.TryFormat() converts the value into a temporary digit buffer, formats those digits into a second buffer, then copies the result to the caller's span. The patch adds a new writer that puts the digits directly into that span, which removes both temporary buffers and the final copy.

It applies only to the invariant culture with the default format, or G without a precision. Other formats and cultures take the old path.

A decimal stores an integer coefficient and a scale, the number of digits after the decimal point. 12345.6700m is 123456700 with scale 4, which is why its trailing zeros survive formatting. When the coefficient fits in 64 bits and the scale is 2 or 4, one DivRem splits the whole and fractional parts. For 12345.6700m, dividing the stored coefficient 123456700 by 10,000 gives quotient 12345 and remainder 6700, and the writer puts them on either side of the decimal point.

C#
private static unsafe bool TryFormatInvariantDecimalSmallScale<TChar>(ulong coefficient, bool negative, int scale, Span<TChar> destination, out int charsWritten)
    where TChar : unmanaged, IUtfChar<TChar>
{
    (ulong whole, ulong fraction) = scale == 2 ? Math.DivRem(coefficient, 100ul) : Math.DivRem(coefficient, 10_000ul);
    int signLength = negative && coefficient != 0 ? 1 : 0;
    int pointIndex = signLength + FormattingHelpers.CountDigits(whole);
    int length = pointIndex + 1 + scale;
    if (length > destination.Length)
    {
        charsWritten = 0;
        return false;
    }

    fixed (TChar* buffer = &MemoryMarshal.GetReference(destination))
    {
        if (signLength != 0)
            buffer[0] = TChar.CastFrom('-');

        TChar* point = buffer + pointIndex;
        UInt64ToDecChars(point, whole);
        *point = TChar.CastFrom('.');
        if (scale == 2)
            WriteTwoDigits((uint)fraction, point + 1);
        else
            WriteFourDigits((uint)fraction, point + 1);
    }

    charsWritten = length;
    return true;
}

Other values take the old path. It writes all the digits at the end of the destination, then moves the whole-number digits one place left to make room for the decimal point.

Show the general path
C#
// In Number.TryFormatDecimal, after parsing the format:
if (digits == -1 && (fmt | 0x20) == 'g' && ReferenceEquals(info, NumberFormatInfo.InvariantInfo))
    return TryFormatInvariantDecimalGeneral(value, destination, out charsWritten);

[MethodImpl(MethodImplOptions.NoInlining)]
internal static unsafe bool TryFormatInvariantDecimalGeneral<TChar>(decimal value, Span<TChar> destination, out int charsWritten)
    where TChar : unmanaged, IUtfChar<TChar>
{
    int scale = value.Scale;
    if (value.High == 0 && scale is 2 or 4) // Here is the optimized path
        return TryFormatInvariantDecimalSmallScale(value.Low64, decimal.IsNegative(value), scale, destination, out charsWritten);

    UInt128 coefficient = new(value.High, value.Low64);
    int integralDigits = FormattingHelpers.CountDigits(coefficient) - scale;
    int signLength = decimal.IsNegative(value) && coefficient != 0 ? 1 : 0;
    int length = signLength + Math.Max(integralDigits, 1) + (scale == 0 ? 0 : scale + 1);

    if (length > destination.Length)
    {
        charsWritten = 0;
        return false;
    }

    if (signLength != 0)
        destination[0] = TChar.CastFrom('-');

    fixed (TChar* buffer = &MemoryMarshal.GetReference(destination))
        UInt128ToDecChars(buffer + length, coefficient);

    if (scale != 0)
    {
        if (integralDigits <= 0)
        {
            destination[signLength] = TChar.CastFrom('0');
            destination[signLength + 1] = TChar.CastFrom('.');
            destination.Slice(signLength + 2, -integralDigits).Fill(TChar.CastFrom('0'));
        }
        else
        {
            // Move the integral digits left one place to open the decimal point.
            destination.Slice(signLength + 1, integralDigits).CopyTo(destination.Slice(signLength));
            destination[signLength + integralDigits] = TChar.CastFrom('.');
        }
    }

    charsWritten = length;
    return true;
}

Stock and patched .NET 11 each passed 34,152 decimal formatting tests.

A separate check passed across all 50,112 decimal cases in UTF-8 and UTF-16. It covered every scale from 0 to 28, both signs, and coefficients on both sides of the 64-bit boundary. Trailing zeros were preserved, negative zero at scale 4 printed as 0.0000, and destinations one byte or character too short failed without writing.

Benchmark#

PriceUtf16 calls decimal.TryFormat() with G and the invariant culture to format -12345.6700m into a reused 64-character char span. One operation writes 11 characters, or 22 bytes.

Metric Before After Change
Mean latency (ns/op) 16.72 6.85 59.0% lower
Managed allocation (B/op) 0 0 0 B/op
Throughput (MB/s) 1,316 3,212 144.1% higher

Results

Method Job Mean Error StdDev Ratio Allocated Alloc Ratio
PriceUtf16 stock 16.720 ns 0.1153 ns 0.0833 ns 1.00 - NA
PriceUtf16 patched 6.849 ns 0.4161 ns 0.3249 ns 0.41 - NA
FrenchControl stock 16.944 ns 0.2378 ns 0.1720 ns 1.00 - NA
FrenchControl patched 17.056 ns 0.1000 ns 0.0661 ns 1.01 - NA
PrecisionControl stock 18.036 ns 0.1255 ns 0.0830 ns 1.00 - NA
PrecisionControl patched 18.003 ns 0.1883 ns 0.1470 ns 1.00 - NA

FrenchControl uses the fr-FR culture and PrecisionControl uses F2, so neither reaches the new writer.

Bonus: With the default format, Utf8Formatter.TryFormat() goes through decimal.TryFormat(), which looks up the culture's number format and parses the format string before it reaches the new writer. A two-line change calls the writer directly instead:

C#
public static bool TryFormat(decimal value, Span<byte> destination, out int bytesWritten, StandardFormat format = default) =>
    format.IsDefault
        ? Number.TryFormatInvariantDecimalGeneral(value, destination, out bytesWritten)
        : FormattingHelpers.TryFormat(value, destination, out bytesWritten, format);

Utf8JsonWriter formats decimals with Utf8Formatter.TryFormat(), so JSON output gets both this change and the new writer. There is still a speedup without the patch to Utf8Formatter.TryFormat(), but it is much faster (about 2×) when Utf8Formatter.TryFormat() calls the writer directly.

The Utf8 rows call Utf8Formatter.TryFormat(). WriteJsonAmounts uses Utf8JsonWriter and writes 256 decimals into a 2,583-byte JSON array.

Method Job Mean Error StdDev Ratio Allocated Alloc Ratio
PriceUtf8 stock 15.914 ns 0.1591 ns 0.1052 ns 1.00 - NA
PriceUtf8 patched 3.798 ns 0.0377 ns 0.0295 ns 0.24 - NA
CentsUtf8 stock 14.706 ns 0.5325 ns 0.3522 ns 1.00 - NA
CentsUtf8 patched 3.593 ns 0.0531 ns 0.0384 ns 0.24 - NA
WideUtf8 stock 39.965 ns 0.2804 ns 0.2189 ns 1.00 - NA
WideUtf8 patched 20.086 ns 0.1437 ns 0.1122 ns 0.50 - NA
TinyUtf8 stock 31.099 ns 1.1725 ns 0.9154 ns 1.00 - NA
TinyUtf8 patched 4.378 ns 0.0798 ns 0.0623 ns 0.14 - NA
ZeroUtf8 stock 11.200 ns 0.0973 ns 0.0703 ns 1.00 - NA
ZeroUtf8 patched 2.672 ns 0.0212 ns 0.0166 ns 0.24 - NA
WholeUtf8 stock 29.727 ns 0.2685 ns 0.1942 ns 1.00 - NA
WholeUtf8 patched 6.150 ns 0.0406 ns 0.0293 ns 0.21 - NA
WriteJsonAmounts stock 5,090.823 ns 35.0120 ns 27.3350 ns 1.00 - NA
WriteJsonAmounts patched 1,762.268 ns 11.4597 ns 8.2861 ns 0.35 - NA

Reproduce#

With the .NET 11 SDK on x64 Linux or x64 Windows, run this from the extracted benchmark directory.

Shell
dotnet run -c Release

The benchmark loads the bundled stock and patched libraries. Both were built from dotnet/runtime commit deae2e32bf0e018e09d64597b7c59b62b73bb3ce.

Download the patch with tests | Download the Linux benchmark | Download the Windows benchmark