From 738e67df59e8dcf799797290459b6daec0321862 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <lic@highgo.com>
Date: Wed, 31 Dec 2025 16:06:33 +0800
Subject: [PATCH v1] nbtree: Cache operator family OID in _bt_setup_array_cmp

Avoid redundant indexing into the rd_opfamily array by caching the
operator family OID in a local variable.

Previously, _bt_setup_array_cmp performed the lookup for the operator
family twice in the cross-type comparison logic path. By fetching
the value once after the early-return check, we make the code slightly
more efficient and significantly more readable.

The assignment is placed after the (elemtype == opcintype) check to
ensure the work is only performed when a cross-type lookup is actually
required.

Author: Chao Li <lic@highgo.com>
---
 src/backend/access/nbtree/nbtpreprocesskeys.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/nbtree/nbtpreprocesskeys.c b/src/backend/access/nbtree/nbtpreprocesskeys.c
index 5b251c5058d..617797d0b08 100644
--- a/src/backend/access/nbtree/nbtpreprocesskeys.c
+++ b/src/backend/access/nbtree/nbtpreprocesskeys.c
@@ -2656,6 +2656,7 @@ _bt_setup_array_cmp(IndexScanDesc scan, ScanKey skey, Oid elemtype,
 	Relation	rel = scan->indexRelation;
 	RegProcedure cmp_proc;
 	Oid			opcintype = rel->rd_opcintype[skey->sk_attno - 1];
+	Oid			opfamily;
 
 	Assert(skey->sk_strategy == BTEqualStrategyNumber);
 	Assert(OidIsValid(elemtype));
@@ -2674,6 +2675,8 @@ _bt_setup_array_cmp(IndexScanDesc scan, ScanKey skey, Oid elemtype,
 		return;
 	}
 
+	opfamily = rel->rd_opfamily[skey->sk_attno - 1];
+
 	/*
 	 * Look up the appropriate cross-type comparison function in the opfamily.
 	 *
@@ -2685,8 +2688,7 @@ _bt_setup_array_cmp(IndexScanDesc scan, ScanKey skey, Oid elemtype,
 	 * incomplete, but only in cases where it's quite likely that _bt_first
 	 * would fail in just the same way (had we not failed before it could).
 	 */
-	cmp_proc = get_opfamily_proc(rel->rd_opfamily[skey->sk_attno - 1],
-								 opcintype, elemtype, BTORDER_PROC);
+	cmp_proc = get_opfamily_proc(opfamily, opcintype, elemtype, BTORDER_PROC);
 	if (!RegProcedureIsValid(cmp_proc))
 		elog(ERROR, "missing support function %d(%u,%u) for attribute %d of index \"%s\"",
 			 BTORDER_PROC, opcintype, elemtype, skey->sk_attno,
@@ -2707,8 +2709,7 @@ _bt_setup_array_cmp(IndexScanDesc scan, ScanKey skey, Oid elemtype,
 	 * non-cross-type comparison procs for any datatype that it supports at
 	 * all.
 	 */
-	cmp_proc = get_opfamily_proc(rel->rd_opfamily[skey->sk_attno - 1],
-								 elemtype, elemtype, BTORDER_PROC);
+	cmp_proc = get_opfamily_proc(opfamily, elemtype, elemtype, BTORDER_PROC);
 	if (!RegProcedureIsValid(cmp_proc))
 		elog(ERROR, "missing support function %d(%u,%u) for attribute %d of index \"%s\"",
 			 BTORDER_PROC, elemtype, elemtype,
-- 
2.39.5 (Apple Git-154)

