Re: Speed up lpad() and rpad() for one-byte padding strings

From: Sehrope Sarkuni <sehrope(at)jackdb(dot)com>
To: Nathan Bossart <nathandbossart(at)gmail(dot)com>
Cc: Pg Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: Speed up lpad() and rpad() for one-byte padding strings
Date: 2026-09-23 22:51:14
Message-ID: CAH7T-ap_DTWMi+5y5AoQfnHPWgw8LTfqXibH-88EFfiT-TnuTA@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Wed, Sep 23, 2026 at 1:19 PM Sehrope Sarkuni <sehrope(at)jackdb(dot)com> wrote:
>
> On Wed, Sep 23, 2026 at 1:09 PM Nathan Bossart <nathandbossart(at)gmail(dot)com> wrote:
> >
> > On Wed, Sep 23, 2026 at 09:41:36AM -0500, Nathan Bossart wrote:
> > > On Wed, Sep 23, 2026 at 10:10:09AM -0400, Sehrope Sarkuni wrote:
> > >> lpad() and rpad() pad one character at a time, calling
> > >> pg_mblen_range() and memcpy() once per padding char. When the padding
> > >> string is a single byte, e.g., lpad(x, n, '0') or rpad(x, n, ' '),
> > >> the padding is that byte repeated, so the attached patch fills it with
> > >> one memset().
> > >
> > > I wonder if we could expand these gains by using SIMD whenever the vector
> > > length is divisible by the padding string length. My hunch is that's where
> > > a lot of the memset() gains come from.
> >
> > Actually, I think we can expand this to any padding string length by
> > copying the padding string once, and then copying from the beginning of the
> > padding to the end repeatedly so that we write double the padding each
> > time. This is a bit like what commit c60e520 added for pglz_decompress().
> > I've attached some proof-of-concept grade patches. This doesn't quite
> > match the performance of your 1-byte fast-path, but it's pretty close and
> > applies to many more cases.
>
> Ah! just saw this after I hit send.

I like your split with the refactor into the separate function first
better. It makes the second piece purely the perf improvement. And
the copy-as-you-count for the first piece is nifty.

Attached is v4 (retroactively referring to my v2, as v3). I stepped
through and renamed it a bit. The rest of it is your v2 with some
updated tests.

Passes tests, CI, and the numbers match my v3.

Regards,
-- Sehrope Sarkuni
Founder & CEO | JackDB, Inc. | https://www.jackdb.com/

Attachment Content-Type Size
v4-0001-Factor-the-padding-loop-out-of-lpad-and-rpad.patch text/x-patch 2.9 KB
v4-0002-Optimize-padding-in-lpad-and-rpad.patch text/x-patch 7.9 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Kiran Kaki 2026-09-23 23:13:54 Re: pg_walinspect: fix LSN validation messages and empty range handling
Previous Message Aleksander Alekseev 2026-09-23 22:39:53 Re: Write skew observed under serializable isolation