wrkm.app
Search
Databases

Andrei Lepikhov: Can numeric be made faster in a PostgreSQL minor release?

In the previous article, I looked at the strengths and weaknesses of the numeric type. A significant part of the extra CPU and RAM usage you see comes from numeric values being stored in variable-length fields and requiring extra memory allocation. When this happens often, for example, with many input numbers, sorting, or lots of groups in GROUP BY, the difference becomes clear, can cause disk spilling and hurt performance.However, real systems usually bound the size and the required p

Editor
Dec 1, 2026 · 17 min read
Andrei Lepikhov: Can numeric be made faster in a PostgreSQL minor release?

In the previous article, I looked at the strengths and weaknesses of the numeric type. A significant part of the extra CPU and RAM usage you see comes from numeric values being stored in variable-length fields and requiring extra memory allocation. When this happens often, for example, with many input numbers, sorting, or lots of groups in GROUP BY, the difference becomes clear, can cause disk spilling and hurt performance.However, real systems usually bound the size and the required precision of their operations, right? So it makes sense to implement a «fast path» for a common limited case like numeric(18,4). Here I describe several improvements that may interest the PostgreSQL community and could, perhaps, be extended to other data types.All the optimisations below follow the same scheme. First, using the value's header and without touching the digits, we decide whether the value qualifies for the fast path. If it does, we compute the answer the short way — without allocations or full unpacking. If not, we pass the value to the existing code, which stays as it was.Two properties follow from this. The result matches the old code bit for bit — down to the hashes used by hash indexes and partitioning machinery. The storage format does not change, and there are no new GUCs, so nothing needs to be enabled. The only price is the check at the entrance, and that check is the main source of potential regressions.ContentsNecessary details on the numeric formatUsing a static bufferAvoiding numeric unpackingFast arithmeticA fast path for aggregatesThe combined effectConclusionNecessary details on the numeric formatPostgreSQL operates on the Numeric structure, which has a 4-byte header and data aligned in memory. However, because its storage format is based on the varlena structure, numeric values are usually stored on disk in a compact form with a 1-byte header. Functions that operate on numeric values work with the four-byte header format and require aligned structures. This forces Postgres to access the memory context more often (in fact, almost always) and allocate additional memory to convert the compact form to the standard one. The numeric header format itself does not change (see the figure below).Unpacking numeric from the short storage format into the full formatIn this short format, varlena stores values of up to 127 bytes, which is more than enough for numeric in practice. So before an operation, the value is unpacked: memory is allocated, a new header is written, and the header and digits are copied byte by byte.In fact, the necessary information can be obtained from the short format too, bypassing the alignment problem. Different operations need different data. The main items are weight, dscale, the sign, and the special-value flag (NaN, ±Inf). Sometimes — for example, when the signs differ in an equality check — the actual digits are not needed at all. The task is to extract the necessary data from the header quickly (see the figure below).Here the two high bits of the first word distinguish the format.  00 and 01 denote long format (00 means the number is positive, 01 - negative), 10 — the short format, 11 — special value, like NaN or ±Inf.These bits, together with the varlena header and the value's length, are exactly the cheap check that every fast path below starts with.Using a static bufferThe first improvement is the simplest: let Postgres unpack the numeric value, but do it in a prepared fixed-size buffer, without allocating new memory from a memory context.Curiously, numeric.c already uses a preallocated buffer, in exactly one place. The function numeric_abbrev_convert(), which builds abbreviated keys for sorting, keeps a preallocated buffer and unpacks short values into it without palloc/pfree. A little further in the file, there is a comment: two palloc/pfree cycles could be saved with persistent buffers, but this “has not so far been considered to be worth the effort”. So here we are effectively testing whether it is worth it.The reasoning is simple: almost every numeric value read from disk arrives with a 1-byte header, so today every operator calls palloc() for every value. A static buffer can hold any number that arrives in the short format, and it can simply be declared as a local variable.The patch set consists of two patches. The first, 0001, introduces such a buffer and does the following:If the value is in the short format and is not an external TOAST pointer, rewrite the header as a 4-byte one, copy the number's body into the buffer, and return a pointer to the buffer.If the header is already 4 bytes and the value is neither compressed nor moved to TOAST, return it as is, without copying.In all other cases (compression or out-of-line storage), use the regular DatumGetNumeric() with allocation and set the needfree flag so that the caller can free the copy.Numeric comparison operators and hash functions use this code, avoiding memory allocations wherever possible.The second patch, 0002, extends the technique to the remaining functions where the value is needed only locally, for intermediate operations: value serialisation, rounding, casts to integer and floating-point types, and so on.Only compressed and TOASTed values bypass the buffer: for them, palloc is still called. Numbers longer than 127 bytes are stored with a 4-byte header and used in place without copying — that was already the case, and the patch does not touch them. In my estimation, the local buffer should work in 99.999% of practical cases.In terms of performance, sorting gains the most, since the comparator is called several times per element. An example with 5 million rows: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 2019 Intel MacBook Pro, execution time is consistently ~6400 ms on current master and ~4900 ms with the patches — almost a quarter faster. Usually I see gains of 15–30%, and in edge cases with several numeric values, up to 35%. But, of course, much depends on the workload.The sum(numeric) aggregate deserves a separate mention. Unpacking the argument is the only allocation this aggregate needs per value. By removing it, we save not only the palloc() call but also the memory context reset that would otherwise happen on every row. Here I expect a speedup of 10% or more.The effect is substantial, but it is even more interesting to examine whether the core has other places where a value is allocated and unpacked repeatedly just to perform a primitive operation. That could give PostgreSQL a good performance boost.Avoiding numeric unpackingThe next step in the same area: what if we perform the operation without unpacking the value at all? Then we can skip all those allocations and buffer copies. This looks doable for equality operations, where EQ/NEQ only need to establish whether the values are identical — and that can be done (if there is no compression or encryption) by comparing the bytes of the number's body and a few bits, such as the sign and the position of the decimal point.To check a = b in a condition — say, a JOIN of two tables — we have palloc, memcpy and pfree for every numeric in the packed format, plus a full comparison in cmp_numerics(). The cmp_numerics function is a universal comparator — it also serves the «greater than» and «less than» operations, which makes it rather expensive. Since we don't need the order to establish equality, we don't need to reconstruct the numbers themselves either - a simple byte-wise memcmp is usually enough.So the basic algorithm is simple:Check for compression or TOAST. For such values, call cmp_numerics().If the values are special (NaN or ±Inf), match them and return the result immediately.If the headers are identical and the lengths are equal, compare the bytes right away: identity proves the numbers are equal.If the steps above haven't finished the job, move to a slightly more complex stage - extract the weight, the sign, and the number of bytes the digits occupy.If the weights, the digit byte counts, or the signs differ, the numbers are not equal. Otherwise, compare the digits themselves byte by byte.The result of memcmp(digits_left, digits_right) gives the exact answer.As usual, there are nuances. For example, we keep in mind the unlikely cases where an incoming number is written as 0XXX or XXXX.XX00 (with zeros at the beginning or the end). The current core code makes this impossible, but who knows what exotic extensions may bring — an FDW, for example, could be a source of such non-standard values, and Postgres must not fail on them. So wherever such a zero could affect the answer, the fast path gives no answer, and the old code runs.What about performance?A simple SELECT on 10 million rows shows the following speedup:CREATE TEMP TABLE t (x numeric(12,8)); INSERT INTO t SELECT random() FROM generate_series(1,1E7); ANALYZE t; SELECT x FROM t t1 WHERE x = 42.42;Execution time is ~300 ms on the current master and ~220 ms on the patched version.The change in execution time for other combinations of conditions:WHERE a = b, same scale — −39%WHERE a b — −31%WHERE a = b, other scale — −30%k = constant of another scale — −27%k IN (seven constants) — −44%In my mind, the most common (and critical) case involves numbers with different scales (not TOASTed or compressed). The implementation seems to demonstrate a nice 30% speedup, underpinned by the sign and length fast-return checks.The second place where the same idea applies is numeric hashing. This operation needs only the weight and the bytes that hold the digits themselves: the sign and dscale are not needed. NaN and ±Inf simply hash to 0. So there is no point in unpacking the number. Let's apply the same trick: check that the necessary information can be extracted from the number quickly, then, using the same algorithm as above, extract the weight and a pointer to the digits, hash them — and that's it!The change in execution time here is roughly as follows (the first patch alone / with the hashing patch applied on top):GROUP BY one key — −23% / −32%GROUP BY ten keys — −37% / −48%Not that much, but it comes practically for free, so why not use it?I wonder whether it makes sense to extend this hack to other data types. What if short bytea fields gained a speedup as well?Fast arithmeticSo comparison and hashing work directly on the packed value, but addition and multiplication produce a new number, and at first glance there is no way to avoid unpacking and full computation.Today, addition, subtraction, and multiplication perform the following common steps:Both input arguments are unpacked, and a NumericVar structure is built from each.Then add_var(), sub_var(), or mul_var() compute the result digit by digit in base 10000 (a direct analogue of school long arithmetic).make_result() allocates memory and packs the answer back into the storage format.Each stage is designed for numbers of arbitrary length. However, a value from a typical numeric(12,2) column occupies only three or four such «digits», and the arithmetic itself accounts for only a small part of the work in this chain.The reasoning here is that a typical incoming number fits comfortably into machine integers. Then the result can be computed in them and written straight into the storage format — without NumericVar and without intermediate buffers. Everything that does not fit is computed the old way.The patch set consists of three patches. The first is preparatory: it extracts a function numeric_build_result() that assembles a finished value directly from an array of digits. The second adds a fast path for multiplication. The third adds a fast path to addition and subtraction. Are there more arithmetic operations to extend the positive effect of this idea?Omitting the details, the addition algorithm is as follows:Check both operands: the value is neither compressed nor TOASTed, the numeric header is short, and there are no more than five digits. Otherwise — fallback.Extract weight, dscale, and sign from the headers.Use the weights to determine how many digit positions both numbers occupy together once aligned on the decimal point. Simply put, 1.01 + 1.01E9 can be computed via the fast path, but 1.01 and 1E-20 cannot.Convert both operands to int64 and perform the operation.Transform the result back into base-10000 numeric digits and pass them to numeric_build_result().Multiplication is simpler, because nothing needs aligning: the weight and dscale of the result are obtained from the headers by addition.Regressions. An operation that does not take the fast path wastes instructions on the check. So it was important to optimise these checks and decide quickly by analysing only the number's header.I was lucky to measure the performance of this feature on three cloud machines in Google Cloud: Intel Emerald Rapids, AMD Turin, and Arm Neoverse-V2, gcc 14.2, a 2-million-row table (only the relevant columns are shown):CREATE TABLE g AS SELECT (random() * 100000)::numeric(12,2) AS v, (0.001 + random() * 100)::numeric(8,3) AS q FROM generate_series(1, 2000000); SELECT count(v + q) FROM g;The change in execution time, Intel / AMD / Arm:count(v * q) — −37% / −28% / −20%count(v + q) — −45% / −35% / −30%count(v - q) — −43% / −35% / −29%WHERE v + q > v * 1.1 — −52% / −34% / −29%sum(price * (1 - disc) * (1 + tax)) — −39% / −22% / −27%TPC-H Q1-like query — −37% / −22% / −22%The spread between processors is large: the same addition gets 45% faster on Intel and 30% faster on Arm. With clang 19, the gain is more modest — 17 to 25% on the same query.There is a downside too. The fast path rejects operations with wide operands like numeric(30,6), but the effect of fast arithmetic on them stays within measurement noise (±3%). Only one regression is clearly visible: when both numbers are short but too far apart in digit positions, and the fast path has to be rejected late. Such an addition becomes 6% slower on AMD and 3% slower on Arm.The addition threshold for fast arithmetic is set by the width of int64. I wonder whether it is worth moving it further by computing in int128? Columns like numeric(24,2) currently take the general path.A fast path for aggregatesAggregates on numeric have received optimisations before (see, for example, commits 9cca11c and 69c8fbac201), but now that portable int128 support covers all supported platforms, fast-path tricks have become possible here as well.The idea of this optimisation for sum/avg(numeric) is as simple as all the previous ones. The transition-state structure of a numeric aggregate needs 144 bytes of extra memory allocation for each group, which, given that Postgres rounds the size of an allocated memory chunk to the next power of two, means 256. And many fields are rarely used — all those NaN or ±Inf counters, for example.Here the scheme is the same, but the decision is made for a whole group rather than for a single value. Suppose that a typical aggregate result, by magnitude and scale, can almost always be stored in an int128. The optimisations for incoming values are already in place thanks to the features described above, so this assumption gives us only fast accumulation in a fixed-type container. We only need to a) introduce an overflow-checked addition (to «promote» the state to the «universal» numeric aggregate state) and b) move the fields that only the universal state needs into a separate structure with lazy initialisation.The CPU savings here are small: before accumulating into an int128, we need to convert numeric → int128, and only then can we do the fast computation. The main benefit appears with a large number of groups in HashAggregate (here, again, the ERPs show their ears), especially with parallel aggregation, where both the Partial and the Finalize nodes of the plan allocate memory for each group. Meanwhile, the size of the main aggregate structure — which, by our hypothesis, is almost always enough — shrinks to 64 bytes.Let's see how all this affects aggregate computation. The speedup here depends mostly on memory, so let's focus on this stable metric and see how much the optimisation reduces the aggregate's memory consumption. Let's take the simple 2-million-row table g from the previous section:sum(v), 500k groups — 192 MB on master, 80 MB with the patch (−58%)sum(w), 500k groups — 240 MB on master, 80 MB with the patch (−67%)sum(x), 500k groups — 240 MB on master, 208 MB with the patch (−13%)sum(v), 2M groups — 744 MB on master, 288 MB with the patch (−61%)The combined effectTo understand the total impact of the optimisations described above, let's return to the example query from the original article.Let's benchmark execution of a quite typical multi-aggregate query on the table with double precision columns and the numeric ones:SELECT f008_type, f008_rtref, f008_rrref, f009rref, f010rref, f011_type, f011_rtref, f011_rrref, f012, f013rref, f014rref, f015rref, f016rref, SUM(v1), SUM(v2), SUM(v3), SUM(v4), SUM(v5), SUM(v6), SUM(v7) FROM bench_shagg_ GROUP BY f008_type, f008_rtref, f008_rrref, f009rref, f010rref, f011_type, f011_rtref, f011_rrref, f012, f013rref, f014rref, f015rref, f016rref;Use the same table schema, with only one difference in the number format: double precision in one table and numeric(15,2) in the other.Each table has 3 million rows and is about 1.07 GB on disk. They form 592,000 groups, about 5 rows each. The values range from 0.00 to 999.99, so every numeric stays small enough for the short fast paths.Comparing the current master with and without the whole patchset applied, we can see the effect:The query over double has not changed as expected. But aggregation over numeric has become noticeably faster: the query runs in ~2.8 s instead of the previous ~9.4 s. And memory consumption has dropped from ~1.8 GB to ~480 MiB. Not bad for a minor upgrade!ConclusionWhere can you see the effect of these optimisations in practice? In principle, you can gather the patches from the community mailing list threads. Also, as far as I know, one of the PostgreSQL forks has already adopted this patch set in its codebase. Nothing needs to be enabled — the fast path triggers automatically, and the results should match the old code bit for bit.With community PostgreSQL, as usual, it may be a long story. The patches are on pgsql-hackers, and you can start digging in the thread Use local buffer for packed numerics. If you find them useful, you can help by reviewing them or running a benchmark. A report on regressions of this approach would be especially valuable.Hopefully, two people are already actively working in this area — David Geier (ex-Swarm64) and Josh Hurst. So we'll see — maybe PostgreSQL 20 will already handle numeric more efficiently.Try it on your data. Reports about problems with numeric may help find new ways to accelerate operations on this type.THE END.December 01, 2026, Madrid, Spain.

Kaynak: Planet PostgreSQL

#PostgreSQL
Share

From other categories