From f9d8e87b98f8a28c18a29e373a0ede76019c99fb Mon Sep 17 00:00:00 2001
From: David Rowley <dgrowley@gmail.com>
Date: Tue, 6 Jul 2021 00:47:05 +1200
Subject: [PATCH v3 3/4] Reduce the number of palloc calls in
 create_range_bounds

The resulting PartitionBoundInfo's datum array elements can be made to
point to a single allocated chunk of memory rather than allocating a
small Datum pointer array for each element.

Author: Justin Pryzby
Reviewed-by: Nitin Jadhav
Discussion: https://postgr.es/m/flat/CAMm1aWYFTqEio3bURzZh47jveiHRwgQTiSDvBORczNEz2duZ1Q@mail.gmail.com
---
 src/backend/partitioning/partbounds.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/src/backend/partitioning/partbounds.c b/src/backend/partitioning/partbounds.c
index e809fb9dda..64bbec05ea 100644
--- a/src/backend/partitioning/partbounds.c
+++ b/src/backend/partitioning/partbounds.c
@@ -617,6 +617,7 @@ create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	int			ndatums = 0;
 	int			default_index = -1;
 	int			next_index = 0;
+	Datum	   *boundDatums;
 
 	boundinfo = (PartitionBoundInfoData *)
 		palloc0(sizeof(PartitionBoundInfoData));
@@ -741,12 +742,13 @@ create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	boundinfo->nindexes = ndatums + 1;
 	boundinfo->indexes = (int *) palloc((ndatums + 1) * sizeof(int));
 
+	boundDatums = (Datum *) palloc(ndatums * key->partnatts * sizeof(Datum));
+
 	for (i = 0; i < ndatums; i++)
 	{
 		int			j;
 
-		boundinfo->datums[i] = (Datum *) palloc(key->partnatts *
-												sizeof(Datum));
+		boundinfo->datums[i] = &boundDatums[i * key->partnatts];
 		boundinfo->kind[i] = (PartitionRangeDatumKind *)
 			palloc(key->partnatts *
 				   sizeof(PartitionRangeDatumKind));
@@ -782,6 +784,8 @@ create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
 		}
 	}
 
+	pfree(rbounds);
+
 	/* Set the canonical value for default_index, if any. */
 	if (default_index != -1)
 	{
-- 
2.30.2

