From cf9dd48306cf0399ea45d540b55aacf744210cef Mon Sep 17 00:00:00 2001 From: David Geier Date: Mon, 10 Nov 2025 15:40:11 +0100 Subject: [PATCH v10 1/3] Use branchless comparisons in btint4cmp and btint8cmp Use the common pg_cmp_s32() and pg_cmp_s64() helpers to implement the built-in B-tree comparison functions for int4 and int8. The previous implementations used conditional branches to distinguish less-than, equal, and greater-than values. The common comparison helpers perform the same three-way comparison without data-dependent branches, which can improve performance for workloads involving frequent integer comparisons while preserving the required comparator result semantics. btint4cmp() and btint8cmp() are PostgreSQL-callable functions invoked through the function manager. They are not inlined at their call sites, so replacing the original conditional implementation does not prevent a compiler from optimizing an inline comparison in contexts where it can see and better optimize the surrounding code. In other words, this change affects the function-manager call path without imposing a performance regression on callers for which the comparison could otherwise have been inlined. The comparison helpers also provide the appropriate handling for the full ranges of int32 and int64 values without relying on subtraction, which could overflow for values near the type limits. --- src/backend/access/nbtree/nbtcompare.c | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/backend/access/nbtree/nbtcompare.c b/src/backend/access/nbtree/nbtcompare.c index 4e3a3a0f7ce..80dec200a3d 100644 --- a/src/backend/access/nbtree/nbtcompare.c +++ b/src/backend/access/nbtree/nbtcompare.c @@ -61,6 +61,7 @@ #include "utils/fmgrprotos.h" #include "utils/skipsupport.h" #include "utils/sortsupport.h" +#include "common/int.h" #ifdef STRESS_SORT_INT_MIN #define A_LESS_THAN_B INT_MIN @@ -194,12 +195,7 @@ btint4cmp(PG_FUNCTION_ARGS) int32 a = PG_GETARG_INT32(0); int32 b = PG_GETARG_INT32(1); - if (a > b) - PG_RETURN_INT32(A_GREATER_THAN_B); - else if (a == b) - PG_RETURN_INT32(0); - else - PG_RETURN_INT32(A_LESS_THAN_B); + PG_RETURN_INT32(pg_cmp_s32(a, b)); } Datum @@ -262,12 +258,7 @@ btint8cmp(PG_FUNCTION_ARGS) int64 a = PG_GETARG_INT64(0); int64 b = PG_GETARG_INT64(1); - if (a > b) - PG_RETURN_INT32(A_GREATER_THAN_B); - else if (a == b) - PG_RETURN_INT32(0); - else - PG_RETURN_INT32(A_LESS_THAN_B); + PG_RETURN_INT32(pg_cmp_s64(a, b)); } Datum -- 2.50.1 (Apple Git-155)