Speed up NUMERICs by skipping varlena unpacking

From: David Geier <geidav(dot)pg(at)gmail(dot)com>
To: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Cc: "lepihov(at)gmail(dot)com >> Andrei Lepikhov" <lepihov(at)gmail(dot)com>, joshhurst77(at)gmail(dot)com, "chenhuimo(dot)mch(at)qq(dot)com >> ChenhuiMo" <chenhuimo(dot)mch(at)qq(dot)com>, Andreas Karlsson <andreas(at)proxel(dot)se>
Subject: Speed up NUMERICs by skipping varlena unpacking
Date: 2026-12-04 12:42:40
Message-ID: 958ab687-0133-4eca-aab6-0c075a1ed434@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

Following up on the discussion summarized in [0] — this is the thread
for approach F: making init_var_from_num() the single point of
representation decoding, so the existing algorithms can operate directly
on short varlena inputs without unpacking.

Motivation
~~~~~~~~~~
The vast majority of NUMERICs in memory are short varlenas, yet
PG_GETARG_NUMERIC()/pg_detoast_datum() palloc a fresh copy for every one
of them. Previous work addressed this per-callsite: e.g. the existing
sort-abbreviation code carries a persistent buffer in NumericSortSupport
to copy short datums into, Andrei's approach expands into a stack buffer
[1], and Chenhui's makes selected paths packed-aware with their own
unpacking [3]. Centralizing the decoding in init_var_from_num() subsumes
the input-access benefits of those approaches, needs no per-callsite
copies or buffers, and can be applied incrementally to all of numeric.c.

How it works
~~~~~~~~~~~~
init_var_from_num() decodes NUMERICs in place into a NumericVar:
header fields are extracted with memcpy (the packed datum may be
unaligned), and var.digits points into the original value — no copy, no
allocation. Because it's inlined, each field is computed at the point of
use — early exits like the specials checks don't pay for decoding fields
that are never read.

With init_var_from_num() handling packed inputs, callers can fetch their
arguments with PG_GETARG_NUMERIC_PACKED instead, reading short varlena
inputs in place with no copy at all. Detoast allocations can then only
occur for external or compressed toasted values, so PG_FREE_IF_COPY()
stays to free those rare copies.

Since digits are no longer copied, they can be unaligned. Reads go
through the read_digit() helper (a 2-byte memcpy); on architectures with
unaligned loads the compiler folds it back into a single 16-bit load. To
catch any missed conversion of a direct digits[i] access, we can build
with -Dc_args=-fsanitize=alignment.

Architectures without, or with slow unaligned-load support — e.g. 32-bit
ARM — will regress in the digits processing code paths. This seems like
a reasonable tradeoff: production workloads run on mainstream
architectures where the gains clearly dominate, and some (most?) of the
cost is repaid by no longer having to unpack.

Patches
~~~~~~~
The patches below convert the frequently used functionality first
(comparisons, sort support, hashing, aggregates), but nothing is
specific to them — the remaining operations can be converted the same
way. I would do that once we agree on the overall approach.

0001: init_var_from_num() handles packed inputs.
0002: cmp_numerics(), the six comparison functions, numeric_smaller()/
larger(), and numeric_fast_cmp() go packed-aware; read_digit()
added.
0003: Remove unnecessary duplicate_numeric() calls. This is not directly
related to the unpacking optimization but certainly useful.
0004: Remove temp buffer from sort support abbreviation code.
0005: hash_numeric()/hash_numeric_extended() go packed-aware,
covering much of the hashing benefit in [2].
0006: Aggregate functions do_numeric_accum() and do_numeric_discard() go
packed-aware, covering the benefit in [3].

0001 in isolation shows no regression on Apple M5 and Ryzen 7 9700X with
Clang 21. That matters because it's the foundation every later patch
builds on. Any slowdown here would compound through the entire series
rather than being attributable to a specific optimization. Establishing
it as performance-neutral makes the wins in the follow-up patches honest.

Apart from being faster, always going through init_var_from_numn() also
makes the code more readable. The targeted optimizations from the other
threads — Josh's fixed-width arithmetic and compact aggregate state [4],
Andrei's equality shortcuts [2], Chenhui's aggregate work [3] — remain
complementary and can be evaluated on top.

The patch set passes regress tests.

Benchmarks
~~~~~~~~~~
I ran attached benchmark which covers a wide range of NUMERIC
functionality, including special values, COPY, in/out and hashing.
Attached is the output for each query compared to master. As not all
functionality is yet optimized, not all queries see a speedup. The
slowdowns are all within noise.

--
David Geier

[0]
https://www.postgresql.org/message-id/52a48fb7-702a-42d0-8a17-d1f19a0e6010%40gmail.com
[1]
https://www.postgresql.org/message-id/flat/5f99450c-4b45-4b82-8498-15461411037c%40gmail.com
[2]
https://www.postgresql.org/message-id/flat/959ad09c-1d66-4260-9c2a-17b2dff03f14%40gmail.com
[3]
https://www.postgresql.org/message-id/flat/tencent_D999DB30A62C6B4D956CA9BADF35CFE91408%40qq.com
[4]
https://www.postgresql.org/message-id/flat/CALJT8Ej89oee83Q-t_x6M1t5QDDRX5U4BzgT0Q-UfHBw%3D7Cb1g%40mail.gmail.com

Attachment Content-Type Size
benchmark_results.txt text/plain 74.9 KB
numeric_benchmark.sql application/sql 29.7 KB
v1-0001-init_var_from_num-supports-packed-varlenas.patch text/x-patch 3.0 KB
v1-0002-Optimize-cmp_numerics.patch text/x-patch 8.7 KB
v1-0003-Remove-unnecessary-calls-to-duplicate_numeric.patch text/x-patch 3.9 KB
v1-0004-Remove-no-longer-needed-sort-support-buffer.patch text/x-patch 3.4 KB
v1-0005-Optimize-hash_numeric-hash_numeric_extended.patch text/x-patch 5.1 KB
v1-0006-Optimize-do_numeric_accum-discard.patch text/x-patch 6.3 KB

Browse pgsql-hackers by date

  From Date Subject
Previous Message Daniel Gustafsson 2026-12-04 12:07:09 Re: [PATCH] Fix off-by-one in -T tablespace mapping length check