Repository navigation
Description
Is your feature request related to a problem or challenge?
Many recent performance PRs make the same kind of change at one call site: process bytes or bits a word at a time instead of a byte at a time or through a libc call. Each PR tunes, tests, and benchmarks its own copy. This has three costs.
The tunings conflict. common_prefix_length in parquet (source, from #10549) compares 32-byte blocks inline because an out-of-line bcmp at 64 bytes measured slower. #12460 compares 8-byte chunks and hands values with a common length above 64 bytes to memcmp because memcmp measured faster there. Both run in the same file of the parquet arrow writer.
Gains don't reach the other copies. #11818 sped up UnalignedBitChunk::count_ones on aarch64. parquet has two count_set_bits functions of its own. The one in the arrow reader (source) calls UnalignedBitChunk::count_ones and got the gain. The one used to skip bit-packed definition levels (source) builds without the arrow feature, where arrow-buffer isn't available, so it has its own loop and didn't get the gain. compare_greater in the parquet column writer (source) still compares slices with a > b while #12460 speeds up the arrow writer's copy of the same comparison.
Work gets duplicated. #12024 and #12042 wrote the same multiply-based bool packing for BooleanBufferBuilder::append_slice at the same time. arrow-buffer has two identical read_u64 functions (bit_util.rs, bit_chunk_iterator.rs). byte_view_key in arrow-ord rank (source) and is_greater_bytes in #12460 (source) each build their own order-preserving integer key from a byte prefix.
Describe the solution you'd like
Give these primitives one home in arrow_buffer::util, next to bit_util and bit_chunk_iterator. Each primitive has one implementation, a test against a naive reference, and benchmark cases for both well-predicted and random input. Add a paragraph to the Performance Improvements section of CONTRIBUTING.md: before adding a word-at-a-time loop at a call site, check arrow_buffer::util and extend or add a primitive there. A PR that tunes a primitive shows results on both x86-64 and aarch64, because every caller inherits the tuning.
For byte comparison, the copies above share a structure with two parts that need different tuning. Most values that differ do so in their first word, so that word should be compared inline in the caller's loop. Values with a long shared prefix need a scan tuned for throughput, kept out of line so it doesn't bloat every caller. #12460 found both effects: inlining its chunk loop cost 2 to 4 points on random strings, and its out-of-line function had to stay a leaf to keep its gain. That suggests three functions:
prefix_key(s: &[u8]) -> u64returns the first 8 bytes as a big-endian integer, zero-padded whensis shorter.prefix_key(a) < prefix_key(b)impliesa < b. Equal keys say nothing. Au128variant covers 16-byte keys likebyte_view_key. Only theu128variant has a caller outsidecmp_bytesso far, so theu64one could stay private until it gets one.common_prefix_len(a: &[u8], b: &[u8]) -> usizeis the out-of-line scan. The choice between inline blocks andmemcmp, and its bound per target, gets made here once. TheDELTA_BYTE_ARRAYencoders, which inline today's scan, would make one call per value.cmp_bytes(a: &[u8], b: &[u8]) -> Orderingcompares the first 8 bytes inline when both values have that many. Shorter values and ties go to an out-of-line function that compares the prefix keys, then scans withcommon_prefix_lenand compares the byte at the mismatch or the lengths. Its result matchesa.cmp(b)for every input.
A prototype showed that this split has to be forced with attributes, because #[inline] alone doesn't hold across crates. With the default release profile, LLVM declined to inline a #[inline] cmp_bytes into parquet's ByteArrayEncoder::write_gather, which inlines the statistics loop of every array type, and kept 24 calls to an out-of-line copy. Marking all of cmp_bytes #[inline(always)] grew write_gather by 18%. Marking only the first-word comparison #[inline(always)], with the rest #[inline(never)], kept it at its current size. With every inlining decision set by an attribute, the split shouldn't depend on each consumer's LTO and codegen-unit settings, though I have checked it only without LTO. The out-of-line scan also lost its leaf status in the prototype to a bounds check whose panic path needed a stack frame. Details like these are easy to break at one call site, which is another reason to review them in one place.
For bitmaps, UnalignedBitChunk and BitChunks already exist. Once parquet can depend on the shared primitives without the arrow feature, it can keep one count_set_bits that calls UnalignedBitChunk::count_ones. arrow-buffer can keep one read_u64.
Each move would be its own PR with benchmark results.
Describe alternatives you've considered
Keeping the current approach costs nothing up front, and each PR stays small. The costs above grow with every new copy.
A generic chunked-scan abstraction, such as a const-generic block width with a closure per block, would cover more cases with one type. It would leave the inlining decisions above to each caller's instantiation, so each caller's generated code would need its own review, and it would be a larger public API to keep stable.
A new crate for these primitives would keep them out of arrow-buffer's API. It would be one more crate to version and release, and parquet would still need it without the arrow feature.
Each crate could keep pub(crate) copies and consolidate within the crate. That avoids new public API, but parquet, arrow-ord, and arrow-buffer would still tune separately.
Additional context
Anything shared between crates has to be pub, so each primitive becomes permanent API under the stability policy. That argues for a few concrete functions with results defined for every input.
parquet uses these primitives in code that builds without the arrow feature, where arrow-buffer is optional. arrow-buffer depends only on bytes, num-bigint, num-traits, and half (Cargo.toml), and parquet already depends on all four without the feature (Cargo.toml), so a required dependency would add no third-party crates.
Is arrow-buffer the right home, and is a required arrow-buffer dependency acceptable for parquet?
cc @alamb @Jefffrey @etseidl @Rich-T-kid @neilconway @adriangb @YUZHEthefool @viirya @waynexia @mightsleep @shanielh
Activity
mbutrovich commentedon Nov 25, 2026
I will try to draft a POC PR today just to understand blast radius and potential tradeoffs to consolidating this sort of stuff (inlining challenges, LTO, etc.).
alamb commentedon Nov 25, 2026
Thank yoU @mbutrovich -- I like the idea of consolidating all our bit manipulation hackery/ tricks. It would be really nice.
This is my preference -- perhaps
arrow-bitutilsor something?alamb commentedon Nov 25, 2026
So if people are generally ok with a new crate for this, I would recommend a POC that:
mbutrovich commentedon Nov 25, 2026
I'll give this a shot, thanks for the feedback!
etseidl commentedon Nov 25, 2026
I wonder if we should roll up some of the ULEB and zigzag decoding as well 🤔 That seems to repeat throughout the various crates.
mbutrovich commentedon Nov 25, 2026
I think it fits. It needs no Arrow types, parquet needs it without the
arrowfeature, and parquet already keeps it inutil/bit_util.rs. The three decoders disagree on an overlong varint:read_varintreturnsNone.read_vlqshifts withwrapping_shland returns a wrong value.BitReader::get_vlq_intpanics on anassert!. It reads RLE run headers andDELTA_BINARY_PACKEDheaders.The encoders are copied the same way (avro,
BitWriter, thrift).mbutrovich commentedon Nov 25, 2026
The draft POC is up in #12470, following the steps in #12467 (comment). It adds
arrow-bitutils, a crate with no dependencies, and moves these into it:bit_chunk_iteratorfromarrow-buffer, which re-exports it, so existing paths don't change.DELTA_BYTE_ARRAYshared-prefix scan, and its statistics byte comparisons, including the comparison from perf(parquet): compare byte-array statistics 8 bytes at a time #12460.rank.The commits read in order, starting with the pure move. The PR description has a table of which copy was kept for each duplicate and why.
parquet uses these without the
arrowfeature. Tuning that went into one copy, such as #11818's aarch64 popcount or #12460's comparison, now reaches every caller. The column writer'scompare_greatergets the #12460 comparison that the PR left for a follow-up.The PR also lists the costs.
arrow-buffer's own calls toBitChunks::newnow cross a crate boundary. Tests and doc examples in the new crate can't useBuffer. Sharing apub(crate)helper such asread_u64would need a new public function.cmp_bytesinlines everything except the scan of a long shared prefix. That differs from the split sketched in the issue description, which kept only the first-word comparison inline. The ULEB128 and zigzag consolidation @etseidl suggested isn't in the POC. Benchmark bot runs will follow on the PR.viirya commentedon Nov 25, 2026
+1 on consolidating. A few points for the POC:
cmp_bytesslow path: I'd keepmemcmp(a[k..].cmp(&b[k..])) for long shared prefixes instead of scanning withcommon_prefix_lenand comparing the byte at the mismatch. perf(parquet): compare byte-array statistics 8 bytes at a time #12460 added its 64-byte bound because a chunk loop lost tomemcmpthere (+22% onlarge_string_non_null, +26% onsmall_string_shared_prefix). The 32-byte block scan was only measured on aarch64, where widths from 16 up tie. Nothing shows it keeps up with glibc's AVX2memcmp. Relatedly, perf(parquet): scan DELTA_BYTE_ARRAY shared prefixes a block at a time #10549 and perf(parquet): compare byte-array statistics 8 bytes at a time #12460 don't really conflict. One needs the mismatch position, whichmemcmpcan't return. The other needs only the order. Both avoid a per-block out-of-line call.UnalignedBitChunkwithoutarrow-buffer. The popcount kernel (count_ones_words) would have to move into the new crate, witharrow-bufferdelegating to it. parquet'sskip_and_count_onescallscount_set_bitsonce per bit-packed run, often a short range.UnalignedBitChunk::new's setup (align_to, prefix/suffix masks) needs a benchmark on short ranges before switching.u64prefix_keycould wait until it does.BitReader::get_vlq_intcan be triggered by a corrupt file. The RLE run header (rle.rs:719) and theDELTA_BINARY_PACKEDheaders read through it, so an overlong varint in page data panics instead of returning an error. That's worth its own fix now. A shared decoder shaped like avro'sread_varint(&[u8]) -> Option<(u64, usize)>would let each crate map the failure to its own error type.arrow-bitutilsmay be too narrow a name.mbutrovich commentedon Nov 25, 2026
Thanks @viirya.
The amd64
arrow_writerruns on #12470 includelarge_string_non_nullandsmall_string_shared_prefix, so they will show whether the block scan keeps up with glibc'smemcmp. If it doesn't, where should the bound go? Inside the inlinedcmp_bytes,memcmpadds a second call target to every caller's loop. Inside the out-of-line scan, the function stops being a leaf, which #12460 found lost its gain.Fair, one needs the position and the other only the order.
#12470 does this: 8041ad3 moves
bit_chunk_iterator, kernel included, intoarrow-bitutils, andarrow-bufferre-exports it.Agreed, and no existing benchmark reaches that path. The arrow reader skips flat optional columns through
PackedDecoder(mod.rs#L118, definition_levels.rs#L467-L483), which already counts withUnalignedBitChunk.BitReader::skip_and_count_onesonly runs whenmax_def_levelis 1 and the levels go throughDefinitionLevelDecoderImpl(decoder.rs#L493, bit_util.rs#L1069). A micro-benchmark of the two on 8 to 504 bit ranges would cover it.The bot builds with thin LTO.
cmp_bytesfixes its split with#[inline(always)]and#[inline(never)], so the split doesn't depend on the LTO setting.BitChunks::newis the open one:arrow-buffer's own calls to it now cross a crate boundary, and theboolean_append_packedruns will show what that costs.Agreed.
prefix_keyis private in #12470.prefix_key_u128has one caller, so I'll drop it too.Agreed.
Agreed that it needs its own issue. I'm not planning to take it on.
Agreed. I'm open to suggestions.
mbutrovich commentedon Nov 25, 2026
@viirya you were right. With the scan,
large_string_non_nullwas 0.76x to 0.89x in every configuration, andstring_dictionary_1pct_cardinalitywas 0.73x to 0.86x on amd64 (for example, amd64 aligned). #12470 now compares the first 8 bytes inline and callsa.cmp(b)for everything else. Both cases are back to 0.94x to 1.07x, and the gains hold:string_dictionary_low_cardinality_400is 1.35x to 1.76x andshort_string_non_null1.19x to 1.46x (amd64 aligned, arm64 aligned). TheDELTA_BYTE_ARRAYcases recovered along with plain encoding, socommon_prefix_lenwasn't the cause.mbutrovich commentedon Nov 30, 2026
Closing in favor of #12516, which tracks the work. The proof of concept and its benchmark results are in #12470.
Here is where each part of the proposal ended up:
arrow_buffer::util, as @alamb suggested (Share word-at-a-time primitives instead of optimizing each call site separately #12467 (comment)). parquet takes a required dependency on that crate, not onarrow-buffer. Its name is still open.prefix_keystays private until it has a second caller (Share word-at-a-time primitives instead of optimizing each call site separately #12467 (comment)).cmp_bytesfollows perf(parquet): compare byte-array statistics 8 bytes at a time #12460's design. In POC: add arrow-bitutils crate for shared word-at-a-time primitives #12470, scanning ties withcommon_prefix_lenlost tomemcmpon long shared prefixes, as @viirya expected (Share word-at-a-time primitives instead of optimizing each call site separately #12467 (comment)).common_prefix_lenstays, forDELTA_BYTE_ARRAY, where the mismatch position is needed.count_set_bitsmoves toUnalignedBitChunkafter a benchmark on short ranges.read_u64keeps a private copy in each crate, because sharing it would need a public function with one caller.