Use local buffer for packed numerics

Поиск
Список
Период
Сортировка
Искать

Use local buffer for packed numerics

От:
Andrei Lepikhov <lepihov@gmail.com>
Дата:
Вложения:
Hi,

After reviewing the current state of the numeric type [1], I noticed there is
still room to improve CPU and memory usage. Here's the first piece of
optimisation ideas.

The support function that sorts abbreviated numerics already uses a local buffer
to avoid calling palloc and pfree for each input value. I believe this method
could work for other numeric operations too.

This makes sense because almost every numeric that comes out of a heap tuple has
a one-byte varlena header and needs to be unpacked into a standard format before
use. Right now, each operator calls palloc() for every numeric value. Using a
preallocated local buffer could save some processing time.

This simple patchset shows how this could work. The first patch, 0001, adds a
structure called NumericLocalBuf, which should be a local variable in the main
operator. It also adds a function, numeric_unpack_local, that unpacks a numeric
into this static buffer or calls palloc if the value is too large.

The second patch, 0002, adds this setup to other numeric-related operations. It
acts as a helper to test how well this optimisation works.

From what I've seen, the usual improvement is between 15% and 30%, with up to
35% speedup in multi-value corner cases. But of course, it depends on the
workload. An example:

CREATE TABLE t_num AS
SELECT i AS id,
  round((random() * 1e8)::numeric, 2)::numeric(12,2) AS a,
  ((i % 1000) * 1.37)::numeric(12,2) AS k1k,
  random()::numeric AS payload
FROM generate_series(1, 5000000) i;

SELECT k1k, a FROM t_num ORDER BY k1k, a OFFSET 4999999;

On my laptop, I see stable 6400ms for the current master branch and 4900ms with
this patchset applied.

What's interesting: it might provide a nice 10% speedup or more for sum(numeric)
because unpack is the only allocation that is needed by the aggregate. So, here
we save not only the palloc() call, but the context reset effort that should be
made on each value.

[1] https://www.pgedge.com/blog/why-is-postgresql-s-numeric-type-so-slow

-- 
regards, Andrei Lepikhov,
pgEdge

Re: Use local buffer for packed numerics

От:
David Geier <geidav.pg@gmail.com>
Дата:
Вложения:
Hi Andrei,

I had looked optimizing NUMERIC as well inspired by [1].

The observation there is similar to your's but goes a step further:

Instead of copying into a scratch buffer to get rid of repeated
alloc/free operations, it completely avoids unpacking the varlena and
instead works directly off of the packed representation.

No longer unpacking results in unaligned memory accesses. To avoid them
I had to change all memory reads to use a function that internally does
a memcpy(). On architectures that allow unaligned memory accesses this
gets compiled down to the original 16-bit memory read.

> After reviewing the current state of the numeric type [1], I noticed there is
> still room to improve CPU and memory usage. Here's the first piece of
> optimisation ideas.

Agreed. It can be a lot faster in almost all areas.

> The support function that sorts abbreviated numerics already uses a local buffer
> to avoid calling palloc and pfree for each input value. I believe this method
> could work for other numeric operations too.
> 
> This makes sense because almost every numeric that comes out of a heap tuple has
> a one-byte varlena header and needs to be unpacked into a standard format before
> use. Right now, each operator calls palloc() for every numeric value. Using a
> preallocated local buffer could save some processing time.
> 
> This simple patchset shows how this could work. The first patch, 0001, adds a
> structure called NumericLocalBuf, which should be a local variable in the main
> operator. It also adds a function, numeric_unpack_local, that unpacks a numeric
> into this static buffer or calls palloc if the value is too large.

Being able to provide the target buffer would allow for similar
optimizations in other code that uses PG_DETOAST_DATUM(). If this is the
route forward, we can also consider changing / extending the API.

> The second patch, 0002, adds this setup to other numeric-related operations. It
> acts as a helper to test how well this optimisation works.
> 
> From what I've seen, the usual improvement is between 15% and 30%, with up to
> 35% speedup in multi-value corner cases. But of course, it depends on the
> workload. An example:

It would be good to know how much we can save on top by directly working
off of the packed representation as outlined above. On x86 that test is
simple to do because unaligned memory accesses are allowed. You would
just replace PG_DETOAST_DATUM() by PG_DETOAST_DATUM_PACKED() and adapt
the macros to work with a packed representation.

I can send you my patch if you like.

Code that supports both, packed and unpacked varlenas, needs to be
crafted carefully though. Just changing the macros such as
NUMERIC_DIGITS(), NUMERIC_NDIGITS(), NUMERIC_IS_SPECIAL() to support
causes regressions because the compiler isn't always able to hoist out
common code but instead repeats all the bit fiddling and case
distinctions each time.

What I ended up doing in my hack branch is having all code always go
through set_var_from_num(). This allowed me to get rid of all the macros
and instead have all varlena packed/unpacked and NUMERIC short/long case
distinctions in a single function that I optimized. This worked nicely
but the diff was pretty big though very repetitive.

> CREATE TABLE t_num AS
> SELECT i AS id,
>   round((random() * 1e8)::numeric, 2)::numeric(12,2) AS a,
>   ((i % 1000) * 1.37)::numeric(12,2) AS k1k,
>   random()::numeric AS payload
> FROM generate_series(1, 5000000) i;
> 
> SELECT k1k, a FROM t_num ORDER BY k1k, a OFFSET 4999999;

Sorting benefits the most because the comparator is called more than
once per element.

> On my laptop, I see stable 6400ms for the current master branch and 4900ms with
> this patchset applied.

Cool! I attached you my benchmark script which exercises a wide range of
NUMERIC functionality. Maybe that's useful. It's by no means complete
but a starting point. Let's improve it together to have something that
covers as much functionality as possible. It's missing e.g. special
NUMERICs like NaN, +Inf, -Inf. You can use the script like that:

\i numeric_benchmark.sql
SELECT * FROM numeric_benchmark_results;

> What's interesting: it might provide a nice 10% speedup or more for sum(numeric)
> because unpack is the only allocation that is needed by the aggregate. So, here
> we save not only the palloc() call, but the context reset effort that should be
> made on each value.

In my tests I saw up to 30% for aggregates. IIRC, you save more than
just the unpacking in the comparator but also some complexity in the
aggregation state handling.

-- 
David Geier

[1]
https://www.postgresql.org/message-id/flat/tencent_D999DB30A62C6B4D956CA9BADF35CFE91408%40qq.com

Re: Use local buffer for packed numerics

От:
Andrei Lepikhov <lepihov@gmail.com>
Дата:
Вложения:
On 18/11/2026 09:06, David Geier wrote:
> Hi Andrei,
> 
> I had looked optimizing NUMERIC as well inspired by [1].
> 
> The observation there is similar to your's but goes a step further:
> 
> Instead of copying into a scratch buffer to get rid of repeated
> alloc/free operations, it completely avoids unpacking the varlena and
> instead works directly off of the packed representation.

Thanks, I missed that thread. After a quick read, I see it more as a complement
to this patch rather than an alternative. I also think local buffers could
become a general way to avoid allocations, not just for numeric cases.

>> The second patch, 0002, adds this setup to other numeric-related operations. It
>> acts as a helper to test how well this optimisation works.
>>
>> From what I've seen, the usual improvement is between 15% and 30%, with up to
>> 35% speedup in multi-value corner cases. But of course, it depends on the
>> workload. An example:
> 
> It would be good to know how much we can save on top by directly working
> off of the packed representation as outlined above. On x86 that test is
> simple to do because unaligned memory accesses are allowed. You would
> just replace PG_DETOAST_DATUM() by PG_DETOAST_DATUM_PACKED() and adapt
> the macros to work with a packed representation.

I can answer part of your question. This patch set is one of three parts of a
numeric speed-up project I implemented a year ago for an ERP workload that is
very heavy in numeric types, and I'm now trying to publish these ideas to the
community.

1. The first part is about unpacking the short numerics into a local buffer
(this thread).
2. The second part uses numeric_eq() and numeric_ne() to derive the result
directly from the stored bytes, with no unpacking at all.
3. Part 3 is a fast 128 bit accumulator for numeric aggregates (not ready for
publishing yet).

I've attached a draft of part 2. It just handles = and <> without any unpacking.
Compared to master, it's typically ~30% faster with clang 19 and ~60% faster
with gcc. So, I guess it is a practical limit for your feature too.

It doesn't overlap with the idea you're referring to, but it has a similar
issue: the code is quite specialized and complex. I'm not sure if an open-source
project would want to take on that challenge. Still, we can try to use common
helpers to make it simpler and more broadly useful.

> 
> I can send you my patch if you like.

Yes, please. I’d like to compare the two.

> 
> In my tests I saw up to 30% for aggregates. IIRC, you save more than
> just the unpacking in the comparator but also some complexity in the
> aggregation state handling.

Thanks for feedback. Let’s see how far we can take this together.

-- 
regards, Andrei Lepikhov,
pgEdge

Re: Use local buffer for packed numerics

От:
David Geier <geidav.pg@gmail.com>
Дата:
Вложения:
>> It would be good to know how much we can save on top by directly working
>> off of the packed representation as outlined above. On x86 that test is
>> simple to do because unaligned memory accesses are allowed. You would
>> just replace PG_DETOAST_DATUM() by PG_DETOAST_DATUM_PACKED() and adapt
>> the macros to work with a packed representation.
> 
> I can answer part of your question. This patch set is one of three parts of a
> numeric speed-up project I implemented a year ago for an ERP workload that is
> very heavy in numeric types, and I'm now trying to publish these ideas to the
> community.
> 
> 1. The first part is about unpacking the short numerics into a local buffer
> (this thread).
> 2. The second part uses numeric_eq() and numeric_ne() to derive the result
> directly from the stored bytes, with no unpacking at all.
> 3. Part 3 is a fast 128 bit accumulator for numeric aggregates (not ready for
> publishing yet).
> 
> I've attached a draft of part 2. It just handles = and <> without any unpacking.
> Compared to master, it's typically ~30% faster with clang 19 and ~60% faster
> with gcc. So, I guess it is a practical limit for your feature too.

Could you run your changes against my benchmark script? Once only with
the scratch buffer change and then combined with also avoiding the
unpacking. You could do that exemplary just for a few operations. It
would be great to talk about concrete, reproducible numbers. On that
note: what architecture are you testing on?

(2) and (3) of your patches are only for a narrow subset of NUMERIC
functionality, are they? I would love to apply the "not unpacking"
change to all of numeric.c.

> It doesn't overlap with the idea you're referring to, but it has a similar
> issue: the code is quite specialized and complex. I'm not sure if an open-source
> project would want to take on that challenge. Still, we can try to use common
> helpers to make it simpler and more broadly useful.

The "not unpacking" change is not complex and pretty repetitive but for
sure a lot of code churn.

>> I can send you my patch if you like.
> 
> Yes, please. I’d like to compare the two.

It's attached. I saw really good results on x86 but some regressions on
M5. That's why I started working on centralizing the case distinction
work scattered throughout all the macros in set_var_from_num() and have
all functions use that. This also makes the code a lot nicer. This
change isn't complete yet, so I cannot send it to you.

I'll share the results on my box with you tomorrow. Right now, I don't
have access to my benchmark machine.

-- 
David Geier

Re: Use local buffer for packed numerics

От:
David Geier <geidav.pg@gmail.com>
Дата:
Вложения:
> It's attached. I saw really good results on x86 but some regressions on
> M5. That's why I started working on centralizing the case distinction
> work scattered throughout all the macros in set_var_from_num() and have
> all functions use that. This also makes the code a lot nicer. This
> change isn't complete yet, so I cannot send it to you.
> 
> I'll share the results on my box with you tomorrow. Right now, I don't
> have access to my benchmark machine.

Attached are the results from my AMD Ryzen 7 9700X. You can see that
there are lots of speedups but also lots of regressions. The regressions
stem from the additional case distinction for if it's a packed /
unpacked varlena that are repeatedly scattered throughout the code via
the NUMERIC_ macros.

I also attached the benchmark script again. The version in my other mail
had a few small issues.

I also attached the patch that shows the idea of having all functions go
via init_var_from_num() and having all "parsing" code happen there in a
single place, only called once per function.

-- 
David Geier

Re: Use local buffer for packed numerics

От:
Andrei Lepikhov <lepihov@gmail.com>
Дата:
On 20/11/2026 09:14, David Geier wrote:
>> It's attached. I saw really good results on x86 but some regressions on
>> M5. That's why I started working on centralizing the case distinction
>> work scattered throughout all the macros in set_var_from_num() and have
>> all functions use that. This also makes the code a lot nicer. This
>> change isn't complete yet, so I cannot send it to you.
>>
>> I'll share the results on my box with you tomorrow. Right now, I don't
>> have access to my benchmark machine.
> 
> Attached are the results from my AMD Ryzen 7 9700X. You can see that
> there are lots of speedups but also lots of regressions. The regressions
> stem from the additional case distinction for if it's a packed /
> unpacked varlena that are repeatedly scattered throughout the code via
> the NUMERIC_ macros.
I wonder what your compiler is.
I test these numeric-related patches on Intel/AMD/ARM platforms with clang/gcc.
For GCC, I do recommend using -mstringop-strategy=libcall. It hides the
performance issue in GCC 12-15. For production code, I usually use a small,
non-committable hack that transforms memcpy(..,..,N) into a series of
memcpy(..,..,8).

-- 
regards, Andrei Lepikhov,
pgEdge


FAQ