From 9a9934d9b5f8f82fc73d89f5e9faa746e176936b Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Fri, 28 Mar 2025 21:12:04 +0530
Subject: [PATCH 3/4] Use length of ec_derives clause list as initial hash
 table size estimation

ec_add_clause_to_derives_hash() adds two entries for every clause which does not
have a constant EM in it. Hence initially the hash table may contain twice the
number of derived clauses. Specify the initial hash table size as four times the
number of existing derived clauses in the list so that we don't require to
expand the hash table immediately when inserting the next clause.

Ashutosh Bapat
---
 src/backend/optimizer/path/equivclass.c | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)

diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index b988db4d7b3..76b8179e285 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -3457,8 +3457,19 @@ ec_build_derives_hash(PlannerInfo *root, EquivalenceClass *ec)
 {
 	Assert(!ec->ec_derives_hash);
 
-	/* Create the hash table */
-	ec->ec_derives_hash = derives_create(root->planner_cxt, 256, NULL);
+	/*
+	 * Create the hash table.
+	 *
+	 * ec_add_clause_to_derives_hash() adds two entries for every clause which
+	 * does not have a constant EM in it. Hence initially the hash table may
+	 * contain twice the number of derived clauses. Specify the initial hash
+	 * table size as four times the number of existing derived clauses in the
+	 * list so that we don't require to expand the hash table immediately when
+	 * inserting the next clause.
+	 */
+	ec->ec_derives_hash = derives_create(root->planner_cxt,
+										 list_length(ec->ec_derives_list) * 4,
+										 NULL);
 
 	foreach_node(RestrictInfo, rinfo, ec->ec_derives_list)
 		ec_add_clause_to_derives_hash(ec, rinfo);
-- 
2.34.1

