Hi,
On Tue, Nov 24, 2026 at 5:58 PM Kyotaro Horiguchi
<[email protected]> wrote:
> 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.
Writing the output to a file gives about the same improvement (median
of 10 runs):
```
time (ms) | wide, 1M rows | 100 int
cols, 200k rows
--------------------------------------+-------------------+-------------------------
COPY TO a server file | 345 -> 257 (-25%) | 521 -> 416 (-20%)
psql COPY TO STDOUT, written to file | 348 -> 260 (-25%) | 514 -> 410 (-20%)
```
> 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.
Your approach works as well. On the two workloads above it gives about
the same gain as the size hints when writing to /dev/null (-23% and
-25%, against -24% and -26%). But it has to be repeated in every
caller that resets a per-row context, such as printtup. And as you
noted, one large row leaves the larger block in place for the rest of
the COPY.
As for keeping the sizes consistent, 37 of the 43 converted send
functions pass a constant or the same length they pass to the write
call, so there is nothing to keep in sync. Only six compute the size
from what they write (numeric, varbit, path, polygon, inet/cidr and
pg_snapshot). Their binary formats have not changed since they were
added, and a wrong size only costs an extra repalloc, not correctness.
If that still seems like too much, I can leave those six on the
default 1 kB.
> 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.
Agreed.
--
Shinya Kato
NTT OSS Center