Re: Speed up lpad() and rpad() for one-byte padding strings - Mailing list pgsql-hackers

From Sehrope Sarkuni
Subject Re: Speed up lpad() and rpad() for one-byte padding strings
Date
Msg-id CAH7T-ap_DTWMi+5y5AoQfnHPWgw8LTfqXibH-88EFfiT-TnuTA@mail.gmail.com
Whole thread
In response to Re: Speed up lpad() and rpad() for one-byte padding strings  (Sehrope Sarkuni <sehrope@jackdb.com>)
List pgsql-hackers
On Wed, Sep 23, 2026 at 1:19 PM Sehrope Sarkuni <sehrope@jackdb.com> wrote:
>
> On Wed, Sep 23, 2026 at 1:09 PM Nathan Bossart <nathandbossart@gmail.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

pgsql-hackers by date:

Previous
From: Aleksander Alekseev
Date:
Subject: Re: Write skew observed under serializable isolation
Next
From: Kiran Kaki
Date:
Subject: Re: pg_walinspect: fix LSN validation messages and empty range handling