Re: Speed up binary COPY TO by not allocating 1 kB per datum

From: Kyotaro Horiguchi <horikyota(dot)ntt(at)gmail(dot)com>
To: shinya11(dot)kato(at)gmail(dot)com
Cc: pgsql-hackers(at)lists(dot)postgresql(dot)org, andres(at)anarazel(dot)de
Subject: Re: Speed up binary COPY TO by not allocating 1 kB per datum
Date: 2026-11-24 08:58:26
Message-ID: 20261124.175826.1523833252761465823.horikyota.ntt@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hello,

At Tue, 24 Nov 2026 11:35:32 +0900, Shinya Kato <shinya11(dot)kato(at)gmail(dot)com> wrote in
> Hi hackers,
>
> The design in the attached patches is Andres's, proposed in [1] and
> last posted as a ten patch series in [2]. I picked the two patches
> that size the send buffer, his v3-0004 and v3-0006, and applied the
> review comments they received [3].
>
> Most send functions start with pq_begintypsend(), which allocates the
> 1 kB default StringInfo buffer. int4send() writes 4 bytes into it.
> printtup and COPY TO call send functions in a per-row memory context
> that is reset after each row, and its keeper block is 8 kB, so with a
> 1 kB chunk per attribute the eighth binary column of a row starts a
> new block. Every row then costs a malloc() and a free() as well as the
> oversized chunks.
...
>
> Thoughts?

While malloc/free and pq_begintypsend() clearly account for a
noticeable portion of the cost in the profiles, it is somewhat
difficult to tell how much improvement we would see in real-world
workloads from a benchmark writing to /dev/null.

Putting that aside, I would prefer to avoid having individual send
functions calculate the expected output size if possible, as it adds
complexity and requires us to keep the size calculations consistent
with the actual serialization code.

As an alternative, how about adaptively increasing the initial block
size of the per-row memory context based on the amount of memory
allocated for the previous row? I tried a quick proof-of-concept
implementation for COPY TO, as attached. One potential drawback of
this approach is that an unusually large memory allocation for a
single row could result in unnecessary memory being retained for
subsequent rows.

The same approach could probably be applied to printtup as well,
though the performance benefit might be less noticeable there.

The optimization of the length word initialization in
pq_begintypsend() also seems effective on its own, so I think that
part is worth doing independently.

Regards,

--
Kyotaro Horiguchi
NTT Open Source Software Center

====
diff --git a/src/backend/commands/copyto.c b/src/backend/commands/copyto.c
index 9ca06ed3e18..e2b0ea81c49 100644
--- a/src/backend/commands/copyto.c
+++ b/src/backend/commands/copyto.c
@@ -1453,8 +1453,34 @@ static inline void
CopyOneRowTo(CopyToState cstate, TupleTableSlot *slot)
{
MemoryContext oldcontext;
+ Size newsize;
+ Size allocated = MemoryContextMemAllocated(cstate->rowcontext, false);

MemoryContextReset(cstate->rowcontext);
+
+ /*
+ * If the previous row required additional memory blocks, recreate the
+ * per-row context with a larger initial block to avoid repeated block
+ * allocation and deallocation for subsequent rows.
+ */
+ newsize = MemoryContextMemAllocated(cstate->rowcontext, false);
+ if (newsize < allocated && newsize < ALLOCSET_DEFAULT_MAXSIZE)
+ {
+ MemoryContext parent = MemoryContextGetParent(cstate->rowcontext);
+
+ while (newsize < allocated && newsize < ALLOCSET_DEFAULT_MAXSIZE)
+ newsize <<= 1;
+
+ newsize = Min(newsize, ALLOCSET_DEFAULT_MAXSIZE);
+
+ MemoryContextDelete(cstate->rowcontext);
+ cstate->rowcontext =
+ AllocSetContextCreate(parent, "COPY TO",
+ ALLOCSET_DEFAULT_MINSIZE,
+ newsize,
+ ALLOCSET_DEFAULT_MAXSIZE);
+ }
+
oldcontext = MemoryContextSwitchTo(cstate->rowcontext);

/* Make sure the tuple is fully deconstructed */
diff --git a/src/backend/libpq/pqformat.c b/src/backend/libpq/pqformat.c
index 8b41aa4f1cb..6f272c64989 100644
--- a/src/backend/libpq/pqformat.c
+++ b/src/backend/libpq/pqformat.c
@@ -325,11 +325,16 @@ void
pq_begintypsend(StringInfo buf)
{
initStringInfo(buf);
- /* Reserve four bytes for the bytea length word */
- appendStringInfoCharMacro(buf, '\0');
- appendStringInfoCharMacro(buf, '\0');
- appendStringInfoCharMacro(buf, '\0');
- appendStringInfoCharMacro(buf, '\0');
+
+ /*
+ * Reserve space for the length word, which pq_endtypsend() fills in.
+ * Zero it, so that a send function that never calls pq_endtypsend()
+ * produces a zero length, which callers reject.
+ */
+ Assert(buf->maxlen >= VARHDRSZ + 1);
+ memset(buf->data, 0, VARHDRSZ);
+ buf->len = VARHDRSZ;
+ buf->data[VARHDRSZ] = '\0';
}

/* --------------------------------

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message vignesh C 2026-11-24 09:09:29 Fix a wrong comment in UpdateDeadTupleRetentionStatus()
Previous Message Andrei Lepikhov 2026-11-24 08:56:00 Re: Use local buffer for packed numerics