Hi, 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%) 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. The patches have no regression tests yet. I will add them in the next version, if this idea is useful. [1] Use local buffer for packed numerics https://www.postgresql.org/message-id/[email protected] -- regards, Andrei Lepikhov, pgEdge
From b9c7237125db298ffaa342cef0356f8078f6bc07 Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <[email protected]> Date: Wed, 18 Nov 2026 14:47:41 +0100 Subject: [PATCH v0 1/2] Decide numeric equality from the stored form numeric_eq() and numeric_ne() detoasted both arguments and called cmp_numerics(). A numeric read from a table usually has a 1-byte varlena header, so detoasting it means a palloc, a memcpy and a pfree whose only purpose is to align the value, and the palloc makes the reset of the per-tuple memory context do real work as well. Equality needs none of that. numeric_quick_eq() decides from the bytes as stored. Two finite values with the same header word and the same length are equal exactly when their bytes are, which takes one memcmp(). Otherwise it repeats the tests of cmp_numerics() on the stored form: NaN and the infinities by header word, then sign, weight, the digits both values have, and the last digit of the longer one. It does not rely on leading and trailing zero digits having been stripped; where such a digit would matter, and for compressed and out-of-line values, it gives no answer and the old code runs. --- src/backend/utils/adt/numeric.c | 300 ++++++++++++++++++++++++++++++- src/tools/pgindent/typedefs.list | 1 + 2 files changed, 297 insertions(+), 4 deletions(-) diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c index ff6dec42010..4fa75bfa0fc 100644 --- a/src/backend/utils/adt/numeric.c +++ b/src/backend/utils/adt/numeric.c @@ -347,6 +347,16 @@ typedef struct hyperLogLogState abbr_card; /* cardinality estimator */ } NumericSortSupport; +/* + * What numeric_quick_eq() can say about two numerics. + */ +typedef enum NumericQuickEq +{ + NUMERIC_QEQ_NO, /* they differ */ + NUMERIC_QEQ_YES, /* they are equal */ + NUMERIC_QEQ_UNKNOWN, /* cannot tell; use cmp_numerics() */ +} NumericQuickEq; + /* ---------- * Fast sum accumulator. @@ -2431,13 +2441,277 @@ numeric_cmp(PG_FUNCTION_ARGS) } +/* + * numeric_stored_data + * Locates the data of a numeric datum in place, starting at the numeric + * header word. The data may be unaligned. Returns false for compressed + * or out-of-line datums, which must be detoasted. + */ +static pg_always_inline bool +numeric_stored_data(Datum d, const char **data, Size *len) +{ + const varlena *v = (const varlena *) DatumGetPointer(d); + Size l; + + /* Values read from a table mostly have a 1-byte header; test it first */ + if (VARATT_IS_SHORT(v)) + { + /* An out-of-line pointer starts with a 1-byte header too */ + if (unlikely(VARATT_IS_EXTERNAL(v))) + return false; + l = VARSIZE_SHORT(v) - VARHDRSZ_SHORT; + *data = VARDATA_SHORT(v); + } + else + { + /* Don't let a corrupt length word send us out of bounds */ + if (unlikely(VARATT_IS_COMPRESSED(v) || VARSIZE(v) < VARHDRSZ)) + return false; + l = VARSIZE(v) - VARHDRSZ; + *data = VARDATA(v); + } + + Assert(l >= sizeof(uint16) && l % sizeof(NumericDigit) == 0); + *len = l; + + return true; +} + +/* + * numeric_stored_parts + * Extracts sign, weight and digits of a finite numeric from data found by + * numeric_stored_data(). Returns false if the data is too short for its + * header format. + * + * NUMERIC_SIGN() and NUMERIC_WEIGHT() need an aligned Numeric, hence the + * open-coded decoding. + */ +static pg_always_inline bool +numeric_stored_parts(uint16 header, const char *p, Size len, + int *sign, int *weight, const char **digits, Size *nbytes) +{ + Size hdrsz; + + Assert((header & NUMERIC_SIGN_MASK) != NUMERIC_SPECIAL); + + if (header & NUMERIC_SHORT) + { + *sign = (header & NUMERIC_SHORT_SIGN_MASK) ? NUMERIC_NEG : NUMERIC_POS; + *weight = ((header & NUMERIC_SHORT_WEIGHT_SIGN_MASK) ? + ~NUMERIC_SHORT_WEIGHT_MASK : 0) | + (header & NUMERIC_SHORT_WEIGHT_MASK); + hdrsz = sizeof(uint16); + } + else + { + int16 w; + + /* No room for the weight: corrupt, let the slow path handle it */ + if (unlikely(len < sizeof(uint16) + sizeof(int16))) + return false; + memcpy(&w, p + sizeof(uint16), sizeof(int16)); + *sign = header & NUMERIC_SIGN_MASK; + *weight = w; + hdrsz = sizeof(uint16) + sizeof(int16); + } + + *digits = p + hdrsz; + *nbytes = len - hdrsz; + + return true; +} + +/* + * numeric_stored_digit + * Returns the digit at a byte offset of a possibly unaligned digit array. + */ +static pg_always_inline NumericDigit +numeric_stored_digit(const char *digits, Size offset) +{ + NumericDigit digit; + + memcpy(&digit, digits + offset, sizeof(NumericDigit)); + return digit; +} + +/* + * numeric_special_eq + * Equality of two stored numerics, given their header words, when at + * least one is NaN or an infinity. Follows cmp_numerics(). + */ +static pg_always_inline bool +numeric_special_eq(uint16 h1, uint16 h2) +{ + bool special1 = (h1 & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL; + bool special2 = (h2 & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL; + + if (special1 != special2) + return false; + if (h1 == NUMERIC_NAN) + return h2 == NUMERIC_NAN; + if (h1 == NUMERIC_PINF) + return h2 == NUMERIC_PINF; + return h2 == NUMERIC_NINF; +} + +/* + * numeric_quick_eq + * Decides whether two numeric datums are equal from their stored form. + * Returns NUMERIC_QEQ_UNKNOWN when cmp_numerics() must decide. + * + * The answer must match cmp_numerics() exactly. Each test mirrors one in + * cmp_var_common() or cmp_abs_common(), and must be kept in sync. + * Unnormalized input (leading or trailing zero digits) causes an UNKNOWN + * result. + */ +static pg_always_inline NumericQuickEq +numeric_quick_eq(Datum d1, Datum d2) +{ + const char *p1; + const char *p2; + Size len1; + Size len2; + uint16 h1; + uint16 h2; + int sign1; + int sign2; + int weight1; + int weight2; + const char *digits1; + const char *digits2; + Size nbytes1; + Size nbytes2; + NumericDigit last; + + if (unlikely(!numeric_stored_data(d1, &p1, &len1) || + !numeric_stored_data(d2, &p2, &len2))) + return NUMERIC_QEQ_UNKNOWN; + + memcpy(&h1, p1, sizeof(uint16)); + memcpy(&h2, p2, sizeof(uint16)); + + /* + * Common case first: values of one column, or of columns with the same + * scale, usually share the header word and the length. + */ + if (h1 == h2 && len1 == len2 && + likely((h1 & NUMERIC_SIGN_MASK) != NUMERIC_SPECIAL)) + { + if (memcmp(p1, p2, len1) == 0) + return NUMERIC_QEQ_YES; + + /* + * Same sign and digit count. If the weights also match, a differing + * digit proves inequality. The short format keeps the weight in the + * header word, the long one in the word right after it. + */ + if (likely((h1 & NUMERIC_SIGN_MASK) == NUMERIC_SHORT)) + return NUMERIC_QEQ_NO; + + Assert(len1 >= sizeof(uint16) + sizeof(int16)); + if (memcmp(p1 + sizeof(uint16), p2 + sizeof(uint16), + sizeof(int16)) == 0) + return NUMERIC_QEQ_NO; + + /* Different weights: leading zero digits may still make them equal */ + } + + if ((h1 & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL || + (h2 & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL) + return numeric_special_eq(h1, h2) ? NUMERIC_QEQ_YES : NUMERIC_QEQ_NO; + + if (unlikely(!numeric_stored_parts(h1, p1, len1, &sign1, &weight1, + &digits1, &nbytes1) || + !numeric_stored_parts(h2, p2, len2, &sign2, &weight2, + &digits2, &nbytes2))) + return NUMERIC_QEQ_UNKNOWN; + + /* No digits means zero, whatever the stored sign and weight */ + if (nbytes1 == 0 || nbytes2 == 0) + return (nbytes1 == nbytes2) ? NUMERIC_QEQ_YES : NUMERIC_QEQ_NO; + + if (sign1 != sign2) + return NUMERIC_QEQ_NO; + + if (weight1 != weight2) + { + /* + * The one with the larger weight is the larger in absolute value, + * unless it starts with a zero digit. + */ + const char *larger = (weight1 > weight2) ? digits1 : digits2; + + if (numeric_stored_digit(larger, 0) != 0) + return NUMERIC_QEQ_NO; + + /* Unnormalized input */ + return NUMERIC_QEQ_UNKNOWN; + } + + if (memcmp(digits1, digits2, Min(nbytes1, nbytes2)) != 0) + return NUMERIC_QEQ_NO; + if (nbytes1 == nbytes2) + return NUMERIC_QEQ_YES; + + /* Extra digits on one side: a nonzero last one proves inequality */ + if (nbytes1 > nbytes2) + last = numeric_stored_digit(digits1, nbytes1 - sizeof(NumericDigit)); + else + last = numeric_stored_digit(digits2, nbytes2 - sizeof(NumericDigit)); + if (last != 0) + return NUMERIC_QEQ_NO; + + /* Unnormalized input */ + return NUMERIC_QEQ_UNKNOWN; +} + +#ifdef USE_ASSERT_CHECKING +/* + * numeric_eq_by_cmp + * Equality via cmp_numerics(), to cross-check numeric_quick_eq(). + */ +static bool +numeric_eq_by_cmp(Datum d1, Datum d2) +{ + Numeric num1 = DatumGetNumeric(d1); + Numeric num2 = DatumGetNumeric(d2); + bool result; + + result = cmp_numerics(num1, num2) == 0; + + if (num1 != DatumGetPointer(d1)) + pfree(num1); + if (num2 != DatumGetPointer(d2)) + pfree(num2); + + return result; +} +#endif + +/* + * numeric_eq, numeric_ne + * Try the stored form first: PG_GETARG_NUMERIC() would copy every value + * with a 1-byte varlena header just to align it. + */ Datum numeric_eq(PG_FUNCTION_ARGS) { - Numeric num1 = PG_GETARG_NUMERIC(0); - Numeric num2 = PG_GETARG_NUMERIC(1); + Numeric num1; + Numeric num2; + NumericQuickEq quick; bool result; + quick = numeric_quick_eq(PG_GETARG_DATUM(0), PG_GETARG_DATUM(1)); + if (quick != NUMERIC_QEQ_UNKNOWN) + { + Assert((quick == NUMERIC_QEQ_YES) == + numeric_eq_by_cmp(PG_GETARG_DATUM(0), PG_GETARG_DATUM(1))); + PG_RETURN_BOOL(quick == NUMERIC_QEQ_YES); + } + + num1 = PG_GETARG_NUMERIC(0); + num2 = PG_GETARG_NUMERIC(1); + result = cmp_numerics(num1, num2) == 0; PG_FREE_IF_COPY(num1, 0); @@ -2449,10 +2723,22 @@ numeric_eq(PG_FUNCTION_ARGS) Datum numeric_ne(PG_FUNCTION_ARGS) { - Numeric num1 = PG_GETARG_NUMERIC(0); - Numeric num2 = PG_GETARG_NUMERIC(1); + Numeric num1; + Numeric num2; + NumericQuickEq quick; bool result; + quick = numeric_quick_eq(PG_GETARG_DATUM(0), PG_GETARG_DATUM(1)); + if (quick != NUMERIC_QEQ_UNKNOWN) + { + Assert((quick == NUMERIC_QEQ_YES) == + numeric_eq_by_cmp(PG_GETARG_DATUM(0), PG_GETARG_DATUM(1))); + PG_RETURN_BOOL(quick == NUMERIC_QEQ_NO); + } + + num1 = PG_GETARG_NUMERIC(0); + num2 = PG_GETARG_NUMERIC(1); + result = cmp_numerics(num1, num2) != 0; PG_FREE_IF_COPY(num1, 0); @@ -8121,6 +8407,10 @@ cmp_var(const NumericVar *var1, const NumericVar *var2) * * Main routine of cmp_var(). This function can be used by both * NumericVar and Numeric. + * + * numeric_quick_eq() reproduces the tests made here, and those made in + * cmp_abs_common(), on the stored form of a numeric. A change to either + * must be made there as well. */ static int cmp_var_common(const NumericDigit *var1digits, int var1ndigits, @@ -11501,6 +11791,8 @@ cmp_abs(const NumericVar *var1, const NumericVar *var2) * * Main routine of cmp_abs(). This function can be used by both * NumericVar and Numeric. + * + * See the note at cmp_var_common() about numeric_quick_eq(). * ---------- */ static int diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index f10eb469266..2d9377a30b0 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1845,6 +1845,7 @@ NullingRelsMatch Numeric NumericAggState NumericDigit +NumericQuickEq NumericSortSupport NumericSumAccum NumericVar -- 2.56.1
From b389639db2d0eef7b89728057af57b0775fa197a Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <[email protected]> Date: Wed, 18 Nov 2026 14:47:41 +0100 Subject: [PATCH v0 2/2] Hash numerics from the stored form hash_numeric() and hash_numeric_extended() detoasted their argument only to read its weight and digits. As in numeric_eq(), for a value with a 1-byte varlena header that is a palloc, a copy and a pfree per call, and a hash aggregate or a hash join calls the hash function for every input row. Find the weight and the digits in the stored bytes instead, with the helpers added for numeric_quick_eq(). Compressed and out-of-line values are detoasted as before. Hash values do not change, because hash indexes and hash partitioning depend on them. --- src/backend/utils/adt/numeric.c | 174 +++++++++++++++----------------- 1 file changed, 80 insertions(+), 94 deletions(-) diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c index 4fa75bfa0fc..479bbe890f7 100644 --- a/src/backend/utils/adt/numeric.c +++ b/src/backend/utils/adt/numeric.c @@ -2999,81 +2999,99 @@ in_range_numeric_numeric(PG_FUNCTION_ARGS) PG_RETURN_BOOL(result); } -Datum -hash_numeric(PG_FUNCTION_ARGS) +/* + * numeric_hash_digits + * Finds the digits to hash and the weight to mix in. Returns false if + * there is nothing to hash. + * + * Leading and trailing zero digits are skipped. The numeric implementation + * *should* guarantee that they are suppressed, but we're paranoid. + */ +static pg_always_inline bool +numeric_hash_digits(const char *p, Size len, bool *special, + int *weight, const char **digits, Size *nbytes) { - Numeric key = PG_GETARG_NUMERIC(0); - uint32 digit_hash; - uint32 result; - int weight; - int start_offset; - int end_offset; - int i; - int hash_len; - NumericDigit *digits; + uint16 header; + int sign; + Size start; + Size end; + + memcpy(&header, p, sizeof(uint16)); /* If it's NaN or infinity, don't try to hash the rest of the fields */ - if (NUMERIC_IS_SPECIAL(key)) - PG_RETURN_UINT32(0); + *special = (header & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL; + if (*special) + return false; + + if (unlikely(!numeric_stored_parts(header, p, len, &sign, weight, + digits, nbytes))) + return false; - weight = NUMERIC_WEIGHT(key); - start_offset = 0; - end_offset = 0; + /* A fraction of a digit at the end is ignored, as NUMERIC_NDIGITS does */ + end = *nbytes - *nbytes % sizeof(NumericDigit); /* - * Omit any leading or trailing zeros from the input to the hash. The - * numeric implementation *should* guarantee that leading and trailing - * zeros are suppressed, but we're paranoid. Note that we measure the - * starting and ending offsets in units of NumericDigits, not bytes. + * The weight is effectively the # of digits before the decimal point, so + * decrement it for each leading zero we skip. */ - digits = NUMERIC_DIGITS(key); - for (i = 0; i < NUMERIC_NDIGITS(key); i++) + start = 0; + while (start < end && numeric_stored_digit(*digits, start) == 0) { - if (digits[i] != (NumericDigit) 0) - break; - - start_offset++; - - /* - * The weight is effectively the # of digits before the decimal point, - * so decrement it for each leading zero we skip. - */ - weight--; + start += sizeof(NumericDigit); + (*weight)--; } /* * If there are no non-zero digits, then the value of the number is zero, * regardless of any other fields. */ - if (NUMERIC_NDIGITS(key) == start_offset) - PG_RETURN_UINT32(-1); + if (start == end) + return false; + + while (numeric_stored_digit(*digits, end - sizeof(NumericDigit)) == 0) + end -= sizeof(NumericDigit); + + *digits += start; + *nbytes = end - start; + + return true; +} + +/* + * hash_numeric + * Hashes the stored form when possible, avoiding an aligned copy. + */ +Datum +hash_numeric(PG_FUNCTION_ARGS) +{ + const char *p; + Size len; + bool special; + int weight; + const char *digits; + Size nbytes; - for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--) + if (unlikely(!numeric_stored_data(PG_GETARG_DATUM(0), &p, &len))) { - if (digits[i] != (NumericDigit) 0) - break; + Numeric key = PG_GETARG_NUMERIC(0); - end_offset++; + p = VARDATA(key); + len = VARSIZE(key) - VARHDRSZ; } - /* If we get here, there should be at least one non-zero digit */ - Assert(start_offset + end_offset < NUMERIC_NDIGITS(key)); + if (!numeric_hash_digits(p, len, &special, &weight, &digits, &nbytes)) + PG_RETURN_UINT32(special ? 0 : -1); /* * Note that we don't hash on the Numeric's scale, since two numerics can * compare equal but have different scales. We also don't hash on the * sign, although we could: since a sign difference implies inequality, * this shouldn't affect correctness. + * + * Mix in the weight, via XOR. */ - hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset; - digit_hash = hash_bytes((unsigned char *) (NUMERIC_DIGITS(key) - + start_offset), - hash_len * sizeof(NumericDigit)); - - /* Mix in the weight, via XOR */ - result = digit_hash ^ weight; - - PG_RETURN_UINT32(result); + PG_RETURN_UINT32(hash_bytes((const unsigned char *) digits, nbytes) ^ + weight); } /* @@ -3083,61 +3101,29 @@ hash_numeric(PG_FUNCTION_ARGS) Datum hash_numeric_extended(PG_FUNCTION_ARGS) { - Numeric key = PG_GETARG_NUMERIC(0); uint64 seed = PG_GETARG_INT64(1); - uint64 digit_hash; - uint64 result; + const char *p; + Size len; + bool special; int weight; - int start_offset; - int end_offset; - int i; - int hash_len; - NumericDigit *digits; - - /* If it's NaN or infinity, don't try to hash the rest of the fields */ - if (NUMERIC_IS_SPECIAL(key)) - PG_RETURN_UINT64(seed); - - weight = NUMERIC_WEIGHT(key); - start_offset = 0; - end_offset = 0; - - digits = NUMERIC_DIGITS(key); - for (i = 0; i < NUMERIC_NDIGITS(key); i++) - { - if (digits[i] != (NumericDigit) 0) - break; - - start_offset++; - - weight--; - } + const char *digits; + Size nbytes; - if (NUMERIC_NDIGITS(key) == start_offset) - PG_RETURN_UINT64(seed - 1); - - for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--) + if (unlikely(!numeric_stored_data(PG_GETARG_DATUM(0), &p, &len))) { - if (digits[i] != (NumericDigit) 0) - break; + Numeric key = PG_GETARG_NUMERIC(0); - end_offset++; + p = VARDATA(key); + len = VARSIZE(key) - VARHDRSZ; } - Assert(start_offset + end_offset < NUMERIC_NDIGITS(key)); + if (!numeric_hash_digits(p, len, &special, &weight, &digits, &nbytes)) + PG_RETURN_UINT64(special ? seed : seed - 1); - hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset; - digit_hash = hash_bytes_extended((unsigned char *) (NUMERIC_DIGITS(key) - + start_offset), - hash_len * sizeof(NumericDigit), - seed); - - result = digit_hash ^ weight; - - PG_RETURN_UINT64(result); + PG_RETURN_UINT64(hash_bytes_extended((const unsigned char *) digits, + nbytes, seed) ^ weight); } - /* ---------------------------------------------------------------------- * * Basic arithmetic functions -- 2.56.1
