Skip to content

Perf: Allocation-free readBigDecimal() fast path for small DECIMAL/NUMERICAL values - #2975

Merged
Ananya Garg (Ananya2) merged 1 commit into
mainfrom
anagarg/perf-datatypes
Jul 24, 2026
Merged

Ananya Garg (Ananya2) merged 1 commit into
mainfrom
anagarg/perf-datatypes

Conversation

@Ananya2

@Ananya2 Ananya Garg (Ananya2) commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR optimizes the per-value DECIMAL/NUMERIC decoder on the ResultSet read path. It removes the throwaway per-cell allocations (a temporary byte[] and an intermediate BigInteger) from readBigDecimal(), while preserving the exact decoded value and the existing lazy-decoding architecture.

On wide-row bulk reads — where every column of every row is decoded — these per-cell temporaries multiply into billions of short-lived objects, creating young-generation GC pressure that shows up as both lower throughput and periodic latency spikes. Targeting the decoder by data type keeps the fix small, self-contained, and provably value-identical.

This is part of a series of read-path performance PRs. A separate PR (perf-read-hotpath) covers the type-agnostic read-path changes (DTV state pooling and the length-prefix reader fast path). This branch is the home for data-type-specific decode optimizations, and will grow as more land.

Measured result on a 601-column × 1M-row × 200-iteration scan with 400 runs (default + fetchSize=512):

Metric Baseline driver This PR Improvement
Average fetch (ms) 52,002 45,150 13.2 % faster
Median fetch (ms) 51,584 44,518 13.7 % faster
P95 fetch (ms) 57,099 51,753 9.4 % faster
Max fetch (ms) 76,393 62,617 18.0 % faster
Standard deviation (ms) 2,891 2,766 4.3 % lower
Spikes > 55 s 42 9 79 % fewer
Spikes > 60 s 10 1 90 % fewer
Spikes > 65 s 2 0 100 % fewer
Throughput (rows/sec) 19,230 22,148 15.2 % higher

Benchmark numbers reflect the effect of the datatype optimizations on this branch and will be updated as additional decoders are added.

Key improvements

  • Decode small DECIMAL/NUMERIC values without an intermediate byte[] or BigInteger.
  • Preserve existing behavior for large-magnitude values and the Always Encrypted decode path.

Changes

1. Allocation-free fast path for readBigDecimal() (Util.java)

readBigDecimal() decodes every DECIMAL/NUMERIC column. The original reverses the little-endian wire bytes into a freshly allocated byte[] and then builds an intermediate BigInteger before constructing the BigDecimal. When the unscaled magnitude fits in a long (precision ≲ 18, the common case), assemble it directly from the wire bytes and build the result with BigDecimal.valueOf(long, scale), skipping both allocations. Larger magnitudes fall back to the original BigInteger path unchanged.

static BigDecimal readBigDecimal(byte[] valueBytes, int valueLength, int scale) {
    int sign = (0 == valueBytes[0]) ? -1 : 1;
    int magnitudeLength = valueLength - 1;

    // Fast path: unscaled magnitude fits in a long — no byte[], no BigInteger.
    if (magnitudeLength <= 8) {
        long magnitude = 0;
        for (int i = magnitudeLength; i >= 1; i--)
            magnitude = (magnitude << 8) | (valueBytes[i] & 0xFFL);
        if (magnitude >= 0)
            return BigDecimal.valueOf(sign * magnitude, scale);
    }

    // Slow path: original BigInteger-based decode, unchanged.
    byte[] magnitude = new byte[magnitudeLength];
    for (int i = 1; i <= magnitude.length; i++)
        magnitude[magnitude.length - i] = valueBytes[i];
    return new BigDecimal(new BigInteger(sign, magnitude), scale);
}

Net effect: for the common case (precision ≲ 18), two per-cell allocations — the reversed magnitude byte[] and the intermediate BigInteger — collapse to zero, and the value is built with cheaper long arithmetic.

Safety. Output is value-identical to the original — BigDecimal.valueOf(long, scale) produces the same compact, long-backed BigDecimal the original path produces for these magnitudes. A magnitude of ≤ 7 bytes always fits a positive signed long; an 8-byte magnitude with its top bit set yields magnitude < 0 and falls through to the unchanged slow path, which also covers every larger value. The input array is only read, never mutated, so all callers (the reader scratch buffer and the Always Encrypted path) are unaffected.


Why this is safe to land

  1. No public-API changes. No new methods, no signature changes, no contract changes.
  2. The fast path is guarded and falls back to the original code whenever the optimization does not apply (any magnitude that does not fit in a positive signed long).
  3. Decoded values are identical. The fast path produces the same BigDecimal the original path produced for the guarded inputs.
  4. No shared mutable state introduced. The decoder reads from the caller-provided buffer and never mutates it.
  5. Defaults unchanged. No new connection property, no opt-in flag. The optimized path is used automatically whenever its guard condition is satisfied.

Benchmark results

Methodology

  • Workload: SELECT * over a 601-column table mixing numeric, string, decimal, and datetime columns
  • Volume: 1,000,000 rows × 200 iterations per run
  • Sample size: 400 runs per build per configuration
  • Configurations: default fetch size + fetchSize=512
  • Builds compared: stock mssql-jdbc (baseline) and this PR
  • Environment: single VM, warmed JVM, no other load

Combined (default + 512 fetchSize, 400 runs each)

Metric Baseline This PR
Average (ms) 52,002 45,150
Median (ms) 51,584 44,518
Min (ms) 47,596 41,520
Max (ms) 76,393 62,617
Range (ms) 28,797 21,097
P90 (ms) 55,095 47,196
P95 (ms) 57,099 51,753
StdDev (ms) 2,891 2,766
CV % 5.56 % 6.13 %
Spikes > 55 s 42 9
Spikes > 60 s 10 1
Spikes > 65 s 2 0
Throughput (rows/sec) 19,230 22,148

Testing

  • Existing test suite: all unit and integration tests pass against this PR. readBigDecimal() is already exercised by the existing suites — getBigDecimal/getObject across DECIMAL/NUMERIC precision and scale combinations, NBCROW null handling, packet-boundary spanning reads, and Always Encrypted decimal columns.
  • Benchmark validation: the 400-run benchmark above was executed end-to-end against a live SQL Server instance with both the baseline and PR builds.
  • Added in Perf: Optimize the ResultSet read path and reduce allocation overhead #2974 WideRowReadTests nested class in ResultSetTest that reads a fat table(10 rows x 601 columns) and asserts the exact value of every cell via type-specific getters. Covers 20 SQL types including both decimal decode paths: decimal(18,0) with an 8-byte magnitude and decimal(38,4) with a larger-than-8-byte magnitude.

@codecov

codecov Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.12%. Comparing base (e55f510) to head (0fe7fc0).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #2975      +/-   ##
============================================
+ Coverage     59.11%   59.12%   +0.01%     
- Complexity     5015     5025      +10     
============================================
  Files           153      153              
  Lines         36332    36339       +7     
  Branches       6644     6647       +3     
============================================
+ Hits          21476    21487      +11     
  Misses        11093    11093              
+ Partials       3763     3759       -4     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This pull request optimizes the DECIMAL/NUMERIC decode hot path in the JDBC driver by adding an allocation-free fast path to Util.readBigDecimal(), reducing per-cell temporary object creation during ResultSet reads.

Changes:

  • Added a fast path that directly assembles small little-endian magnitudes (≤ 8 bytes) into a long and returns BigDecimal.valueOf(long, scale) without allocating a reversed byte[] or creating an intermediate BigInteger.
  • Preserved the existing BigInteger-based fallback path for larger magnitudes (and for 8-byte magnitudes that do not fit in a positive signed long).
@Ananya2
Ananya Garg (Ananya2) merged commit c7ef1a2 into main Jul 24, 2026
24 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Closed/Merged PRs in MSSQL JDBC Jul 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

5 participants