From b503f94124620433d1e8276341079c70d037d360 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Tue, 18 Nov 2025 09:39:59 -0500
Subject: [PATCH v6 07/14] bufmgr: Add one-entry cache for private refcount

Author:
Reviewed-by:
Discussion: https://postgr.es/m/
Backpatch:
---
 src/backend/storage/buffer/bufmgr.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 972eae1fc7b..b7ce4bafdea 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -226,6 +226,8 @@ static HTAB *PrivateRefCountHash = NULL;
 static int32 PrivateRefCountOverflowed = 0;
 static uint32 PrivateRefCountClock = 0;
 static int	ReservedRefCountSlot = -1;
+static int	PrivateRefcountEntryLast = -1;
+
 
 static uint32 MaxProportionalPins;
 
@@ -356,6 +358,8 @@ NewPrivateRefCountEntry(Buffer buffer)
 	res->buffer = buffer;
 	res->data.refcount = 0;
 
+	PrivateRefcountEntryLast = ReservedRefCountSlot;
+
 	ReservedRefCountSlot = -1;
 
 	return res;
@@ -378,6 +382,16 @@ GetPrivateRefCountEntry(Buffer buffer, bool do_move)
 	Assert(BufferIsValid(buffer));
 	Assert(!BufferIsLocal(buffer));
 
+	/*
+	 * It's very common to look up the same buffer repeatedly. To make that
+	 * fast, we have a one-entry cache.
+	 */
+	if (likely(PrivateRefcountEntryLast != -1) &&
+		likely(PrivateRefCountArrayKeys[PrivateRefcountEntryLast] == buffer))
+	{
+		return &PrivateRefCountArray[PrivateRefcountEntryLast];
+	}
+
 	/*
 	 * First search for references in the array, that'll be sufficient in the
 	 * majority of cases.
@@ -392,7 +406,10 @@ GetPrivateRefCountEntry(Buffer buffer, bool do_move)
 	}
 
 	if (match != -1)
+	{
+		PrivateRefcountEntryLast = match;
 		return &PrivateRefCountArray[match];
+	}
 
 	/*
 	 * By here we know that the buffer, if already pinned, isn't residing in
-- 
2.48.1.76.g4e746b1a31.dirty

