Skip to content

Writing a decimal as numeric allocates a short[9] per value #6728

Description

@tamasprincz97-dot

Steps to reproduce

Write any non-null decimal parameter as numeric, or run the existing benchmark:

cd test/Npgsql.Benchmarks
dotnet run -c Release -- --filter '*TypeHandlers.Numeric.Write*' --job short

The issue

DecimalNumericConverter<T>.Write gives PgNumeric.Builder a stack buffer of MaxDecimalNumericDigits (8) shorts:

Span<short> destination = stackalloc short[PgNumeric.Builder.MaxDecimalNumericDigits];

PgNumeric.Builder.Create reserves an upper bound before converting, and allocates if the destination is smaller:

var bitsUpperBound = (bits.Length * (MaxUInt32Scale + 1) + MaxUInt16Scale - 1) / MaxUInt16Scale + 1;
if (bitsUpperBound > destination.Length)
    destination = digitsArray = new short[bitsUpperBound];

For a decimal, bits.Length is 3, so the bound is (3 * 10 + 3) / 4 + 1 = 9. That is more than 8, so every non-null value allocates a short[9] (48 B), and the stack buffer is never used. The same converter is used for byte, short, int, long, float and double mapped to numeric, and for numeric ranges and multiranges.

A decimal never needs more than 8 numeric digits. The 9th slot is the builder's generic headroom, so the buffer is one short too small for the check.

TypeHandlers.Numeric.Write on main (b35800b), BenchmarkDotNet ShortRun, .NET 10.0.14: all 15 benchmark values allocate 48 B per op.

This is unrelated to #6509, which is a read-side bug in PgNumeric.Builder.ToDecimal.

Further technical details

Npgsql version: main (11.0.0-preview.1, b35800b); also present in 10.0.3
PostgreSQL version: any (client side)
Operating system: any

Activity

  1. added 2 commits that reference this issue on Oct 28, 2026
    67447bf
    adc5373
  2. added theissue type on Nov 17, 2026
  3. added this to the 11.0.0 milestone on Nov 17, 2026
  4. modified the milestones: 11.0.0, 12.0.0 on Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions