Re: Numeric equality and hashing without detoasting

From: David Geier <geidav(dot)pg(at)gmail(dot)com>
To: Andrei Lepikhov <lepihov(at)gmail(dot)com>, PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>, Andreas Karlsson <andreas(at)proxel(dot)se>
Subject: Re: Numeric equality and hashing without detoasting
Date: 2026-11-24 14:32:45
Message-ID: f331a89d-7d53-4adf-8221-a5e1ec1d1e7e@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi Andrei,

> This is the second step of the numeric operations optimisation efforts, started
> at [1].
>
> This part is about the idea that the EQ/NEQ operator might avoid unpacking
> operations altogether. A more general routine, cmp_numerics(), is used for < and
>> operations too and needs unpacking, so the previous thread [1] should help in
> this case.
>
> 0001 makes numeric_eq() and numeric_ne() decide from the bytes as stored. If two
> finite values have the same header word and the same length, one memcmp() gives
> the answer. Otherwise the code repeats the tests of cmp_numerics() on the stored
> form. Compressed, TOASTed, and non-normalised values with leading or trailing
> zero digits, still use cmp_numerics() - but in practice it looks like quite rare
> case.
>
> 0002 applies the same idea to hash_numeric() and hash_numeric_extended(). They
> need only the weight and the digits, so they now read them in place. Hash values
> do not change.
>
> Performance gain might be easily identified by the following test:
>
> CREATE TEMP TABLE t (x numeric(12,8));
> INSERT INTO t SELECT random() FROM generate_series(1,1E7);
> ANALYZE t;
>
> SELECT x FROM t t1 WHERE x = 42.42;
>
> On my Intel Macbook Pro 2019 I see the following numbers:
>
> master ~300 ms, patched ~220 ms.
>
> Other primitives show the following numbers:
>
> WHERE a = b, same scale -39%
> WHERE a <> b -31%
> WHERE a = b, other scale -30%
> k = constant of other scale -27%
> k IN (seven constants) -44%
> GROUP BY one key -32% (0001 alone: -23%)
> GROUP BY ten keys -48% (0001 alone: -37%)

Nice improvements!

> Queries without numeric equality are not affected.
>
> It might seem overcomplicated for these speedup numbers. But it might be an
> approach to speed up operations on other types too. So, I'll leave it here and
> let the community decide.
[1] also provided optimizations for a narrow subset of NUMERIC. I still
don't think that's the way to go. I would prefer an approach that can be
used for all NUMERIC code and that doesn't need two implementations for
packed and unpacked. Fundamentally, all NUMERIC code can operate on
packed representation with the caveat that reads must go through
memcpy() due to possible alignment requirements. That's not so nice
code-wise but doesn't matter for performance as the compiler will turn
the memcpy() back into a single load instruction on architectures that
support unaligned loads.

The approach / draft patch shared in [2] builds on top of
init_var_from_num(). The idea is that all format "parsing" happens only
in that function and the resulting NumericVar is used from that point
on. Reading digits would go through a helper that does a memcpy() to
extract the 16-bit digit in an alignment-friendly way.

A somewhat optimized version of init_var_from_num() could look like
this, with potential for more improvements. Inlining allows the compiler
to discard whatever parts are not needed at the call site.
We should test how smart the compiler is in removing not needed parts
and moving code around so that it's only executed if truly needed (e.g.
ndigits is only computed once it's needed because the function might
return before based on the sign).

inline static void
init_var_from_num(const Numeric num, NumericVar *dest)
{
uint16 header;
bool isHeaderShort;
const char *varData = VARDATA_ANY(num);
const int varSize = VARSIZE_ANY_EXHDR(num);

memcpy(&header, varData, sizeof(header));
isHeaderShort = ((header & 0x8000) != 0);

dest->buf = NULL; /* digits array is not palloc'd */

if (isHeaderShort)
{
dest->ndigits = ((varSize - sizeof(uint16)) / izeof(NumericDigit));
dest->weight = (header & NUMERIC_SHORT_WEIGHT_SIGN_MASK ?
~NUMERIC_SHORT_WEIGHT_MASK : 0) | (header &
NUMERIC_SHORT_WEIGHT_MASK);
dest->sign = (header & NUMERIC_SIGN_MASK) == NUMERIC_SHORT ?
((header & NUMERIC_SHORT_SIGN_MASK) ? NUMERIC_NEG :
NUMERIC_POS) : (header & NUMERIC_EXT_SIGN_MASK);
dest->dscale = (header & NUMERIC_SHORT_DSCALE_MASK) >>
NUMERIC_SHORT_DSCALE_SHIFT;
dest->digits = (NumericDigit *)(varData + sizeof(header));
}
else
{
int16 weight;
memcpy(&weight, varData+sizeof(header), sizeof(weight));

dest->ndigits = ((varSize - sizeof(uint16) - sizeof(int16)) /
sizeof(NumericDigit));
dest->weight = weight;
dest->sign = ((header & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL ?
(header & NUMERIC_EXT_SIGN_MASK) : (header &
NUMERIC_SIGN_MASK));
dest->dscale = header & NUMERIC_DSCALE_MASK;
dest->digits = (NumericDigit *)(varData + sizeof(header) +
sizeof(weight));
}
}

With that also a lot of possibly repeated parsing code from the NUMERIC_
macros would go away, e.g. NUMERIC_IS_SPECIAL(), NUMERIC_IS_NAN(), etc.
all check if the underlying NUMERIC header is long or short. Which
reduces code size and makes it easier for the compiler to generate
efficient code. I've seen the compiler often missing optimizations where
it must assume that a write possibly changes memory that later
computations depend on (maybe because we disabled strict-aliasing in our
builds).

I'm happy to provide a minimal example for a single function from
numeric.c to demo the idea start to end.

--
David Geier

[1]
https://www.postgresql.org/message-id/flat/tencent_D999DB30A62C6B4D956CA9BADF35CFE91408%40qq.com
[2]
https://www.postgresql.org/message-id/flat/5f99450c-4b45-4b82-8498-15461411037c%40gmail.com

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Jim Jones 2026-11-24 14:34:25 Add CHECK_FOR_INTERRUPTS() to XPath result serialisation
Previous Message Ishjaap Singh 2026-11-24 14:28:25 Make jsonpath input report out-of-range numbers softly