Use local buffer for packed numerics
Thread notes
1 note#performance#moderate#enhancement
hackorum-bot#performance#moderate#enhancement
@global #performance #moderate #enhancement
Hi,
After reviewing the current state of the numeric type [1]https://www.pgedge.com/blog/why-is-postgresql-s-numeric-type-so-slow, 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
Attachments:
t259280_1v0-0001-Unpack-short-numerics-on-the-local-buffer.patchtext/plain; charset=UTF-8; name=v0-0001-Unpack-short-numerics-on-the-local-buffer.patchDownload+104-87
v0-0002-Unpack-short-numerics-on-the-stack-in-the-remaini.patchtext/plain; charset=UTF-8; name=v0-0002-Unpack-short-numerics-on-the-stack-in-the-remaini.patchDownload+74-63
Hi Andrei,
I had looked optimizing NUMERIC as well inspired by [1]/messages/by-id/tencent_D999DB30A62C6B4D956CA9BADF35CFE91408@qq.com.
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]: /messages/by-id/tencent_D999DB30A62C6B4D956CA9BADF35CFE91408@qq.com
/messages/by-id/tencent_D999DB30A62C6B4D956CA9BADF35CFE91408@qq.com
Attachments:
numeric_benchmark.sqltext/plain; charset=UTF-8; name=numeric_benchmark.sqlDownload
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
Attachments:
eq-noneq.no-cfbottext/plain; charset=UTF-8; name=eq-noneq.no-cfbotDownload+266-4
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
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
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
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 used GCC 15.2.0 for the results I shared.
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.
But that flag is not used by PostgreSQL upstream. So the final code
needs to perform regardless of that flag.
What exactly doesn't work with GCC 12-15? Is this documented somewhere?
--
David Geier
On 24/11/2026 08:45, David Geier wrote:
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.But that flag is not used by PostgreSQL upstream. So the final code
needs to perform regardless of that flag.What exactly doesn't work with GCC 12-15? Is this documented somewhere?
Yes, it is a well-known issue. See:
1. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95556
2. https://lkml.indiana.edu/hypermail/linux/kernel/2506.1/01504.html
It is related to x86/amd & gcc only. Closed in gcc 16 (at least I don't see any
regression there).
--
regards, Andrei Lepikhov,
pgEdge
On 20/11/2026 09:14, David Geier wrote:
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.
Hi David,
CFBot picked up your patch as the latest patch set for this CF entry [1]https://commitfest.postgresql.org/patch/7662/, and it
now fails on all platforms in the numeric regression test.
The cause I hope is a slip in cmp_numerics(), in the PINF branch:
- else if (var2.sign == NUMERIC_POS)
+ else if (var2.sign == NUMERIC_PINF)
result = 0; /* PINF = PINF */
To keep this entry focused on the local-buffer approach, I'm re-attaching my
patches as v2. They're the same as v0, just rebased onto current master.
Since the no-unpacking direction is a separate piece of work, could you name
experimental patches in this thread with a .txt or .no-cfbot suffix, so CFBot
doesn't pick them up? If you plan to develop that idea further, it might be
worth its own thread and CF entry - just add me in CC.
[1]: https://commitfest.postgresql.org/patch/7662/
--
regards, Andrei Lepikhov,
pgEdge
Attachments:
t259280_9v2-0001-Unpack-short-numerics-on-the-local-buffer.patchtext/plain; charset=UTF-8; name=v2-0001-Unpack-short-numerics-on-the-local-buffer.patchDownload+104-87
v2-0002-Unpack-short-numerics-on-the-stack-in-the-remaini.patchtext/plain; charset=UTF-8; name=v2-0002-Unpack-short-numerics-on-the-stack-in-the-remaini.patchDownload+74-63
CFBot picked up your patch as the latest patch set for this CF entry [1], and it
now fails on all platforms in the numeric regression test.The cause I hope is a slip in cmp_numerics(), in the PINF branch:
- else if (var2.sign == NUMERIC_POS) + else if (var2.sign == NUMERIC_PINF) result = 0; /* PINF = PINF */To keep this entry focused on the local-buffer approach, I'm re-attaching my
patches as v2. They're the same as v0, just rebased onto current master.Since the no-unpacking direction is a separate piece of work, could you name
experimental patches in this thread with a .txt or .no-cfbot suffix, so CFBot
doesn't pick them up?
Sorry for that. I hadn't realized there's already a commitfest entry.
Will do next time.
If you plan to develop that idea further, it might be
worth its own thread and CF entry - just add me in CC.
Will do and open a new thread for it.
--
David Geier
On 19/11/2026 18:33, David Geier wrote:
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?
Here are the benchmarking results on my side, as you requested.
I compared the current master branch and, separately, your patch, my unpack, and
all my four optimisations altogether (unpack, no unpack for EQ/NEQ [1]/messages/by-id/959ad09c-1d66-4260-9c2a-17b2dff03f14@gmail.com, fast
path for arithmetic, and fast path for aggregates [2]/messages/by-id/a3ed87e5-6d93-4694-ab57-76094b600938@gmail.com).
My Intel MacBook Pro 2019 is not the best benchmarking platform already. So, I
usually use Google Cloud for such experiments.
I tried to choose different platforms (Intel/AMD/ARM) with the same compiler
(Clang). According to the Google docs, I used the following architectures: Intel
Xeon 8581C (1), AMD EPYC 9B45 (2), and ARM Neoverse-V2 (3). The total speedup is
as follows.
platform: (1) (2) (3)
master, ms 17926 15531 22211
avoid unpacking −6.1% −5.1% −6.6%
static buffer −5.2% −4.7% −4.3%
all four opts −8.8% −8.2% −7.5%
The exact numbers that your benchmark printed are in the attachment.
My personal lesson from this benchmark, in comparison to my own, is that each
optimisation has its own best case - and your benchmark doesn't cover all of
them. So, it definitely makes sense to consider each of these features separately.
[1]: /messages/by-id/959ad09c-1d66-4260-9c2a-17b2dff03f14@gmail.com
/messages/by-id/959ad09c-1d66-4260-9c2a-17b2dff03f14@gmail.com
[2]: /messages/by-id/a3ed87e5-6d93-4694-ab57-76094b600938@gmail.com
/messages/by-id/a3ed87e5-6d93-4694-ab57-76094b600938@gmail.com
--
regards, Andrei Lepikhov,
pgEdge