Skip to content

perf(arrow-buffer): pack bools branchlessly in BooleanBufferBuilder::append_slice - #12024

Merged
viirya merged 8 commits into
apache:mainfrom
viirya:boolean-append-slice-branchless
Nov 6, 2026
Merged

viirya merged 8 commits into
apache:mainfrom
viirya:boolean-append-slice-branchless

Conversation

@viirya

@viirya viirya commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Which issue does this PR close?

Rationale for this change

BooleanBufferBuilder::append_slice sets one bit at a time behind a data-dependent branch. This is the path the Parquet reader takes to build BooleanArray values (BooleanBuffer::from(&[bool])), and it dominates reading BOOLEAN columns. See the issue for details.

What changes are included in this PR?

For slices of more than 8 values, append_slice now:

  1. fills the first byte up to the next byte boundary (at most 7 values),
  2. packs each following group of 8 bools into one byte with u64::from_le_bytes(bytes).wrapping_mul(0x0102_0408_1020_4080) >> 56, writing whole bytes, and
  3. writes the remaining fewer than 8 values into the last byte.

Steps 1 and 3, and slices of up to 8 values, build their bits in a register with (v as u8) << i and update each byte with a single OR, so no step branches on the values. Up to 8 values touch at most two bytes, which also covers 8 values at an unaligned offset, where no whole byte would be left to pack. The packing path lives in an #[inline(never)] helper so the inlined code for short appends stays small. The unsafe call to set_bit_raw is gone.

The multiply works because each input byte is 0 or 1 (bool as u8): byte i lands on bit 56 + i, and no two partial products overlap, so there are no carries. from_le_bytes makes the result the same on big-endian targets. Whole bytes are written only past the previous length, and those bytes were just zero-filled by advance, so overwriting them is safe, including after truncate.

Also adds a boolean_buffer_builder criterion bench to arrow-buffer, covering 64Ki-value appends, repeated appends of 1 to 7 values, and repeated appends of 8 values at offsets 0 and 3.

Are these changes tested?

Yes. Two new unit tests:

  • test_append_slice_all_byte_patterns checks all 256 patterns of 8 bools, through both the short path and the multiply.
  • test_append_slice_offsets checks every starting bit offset 0..16 against slice lengths 0..100, starting after a truncate, and followed by another append.

Benchmarks, Apple M-series (aarch64), from back-to-back runs of main and this PR:

cargo bench -p arrow-buffer --bench boolean_buffer_builder (offset 3 starts mid-byte; all appends read fresh values):

case main this PR change
64Ki random, offset 0 165.0 µs 1.22 µs −99.3%
64Ki random, offset 3 165.6 µs 1.26 µs −99.2%
64Ki 90% true, offset 0 76.0 µs 1.21 µs −98.4%
64Ki 90% true, offset 3 75.6 µs 1.27 µs −98.3%
64Ki all true, offset 0 94.5 µs 1.21 µs −98.7%
64Ki all true, offset 3 93.7 µs 1.25 µs −98.7%
7168 appends of 1–7 values, random 77.5 µs 18.7 µs −75.9%
7168 appends of 1–7 values, all false 21.8 µs 17.6 µs −19.5%
7168 appends of 8 values, offset 0, random 168.3 µs 17.4 µs −89.7%
7168 appends of 8 values, offset 3, random 169.0 µs 17.2 µs −89.8%
7168 appends of 8 values, offset 0, all false 27.2 µs 17.3 µs −36.2%
7168 appends of 8 values, offset 3, all false 27.2 µs 16.9 µs −37.8%

The existing bench_bool in arrow/benches/builder.rs (BooleanBuilder::append_slice, 64 batches of 8Ki random bools), measured at 31f2c3c:

bench main this PR change
bench_bool 761–773 µs 19.6 µs −97.4%

End to end, reading 1M rows of an optional BOOLEAN column (10% nulls, random values) from an in-memory Parquet file through ParquetRecordBatchReader: 4.95 ms → 2.10 ms (−57.5%), also measured at 31f2c3c. This uses a scenario benchmark I'll propose in a separate PR.

Are there any significant user-facing changes?

No.

viirya and others added 2 commits November 1, 2026 10:51
Covers random, mostly true and all true slices appended at a byte
aligned and an unaligned bit offset.

Co-authored-by: Isaac <[email protected]>
…append_slice

append_slice set each bit with a data dependent branch, which
mispredicts badly on random data. Set bits individually only until the
write position is byte aligned, then pack each 8 bools into a byte with
a multiply, and finish with a per-bit tail.

Co-authored-by: Isaac <[email protected]>
@github-actions github-actions Bot added arrow-core Core crates related to representing arrow data enhancement New feature/addition labels Nov 1, 2026
@viirya
viirya requested a review from sunchao November 1, 2026 22:17
let (chunks, remainder) = rest.as_chunks::<8>();
for (dst, chunk) in buffer[byte_offset..].iter_mut().zip(chunks) {
let bytes: [u8; 8] = std::array::from_fn(|i| chunk[i] as u8);
let packed = u64::from_le_bytes(bytes).wrapping_mul(0x0102_0408_1020_4080) >> 56;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice trick. On x86_64 with bmi2 feature this could also be written as

std::arch::x86_64::_pext_u64(u64::from_le_bytes(bytes), 0x01010101_01010101)

But I think that only saves a single cycle for the shift. Very cool that there is a portable alternative.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Yes, _pext_u64 with 0x0101_0101_0101_0101 gives the same packed byte directly. I'd keep the multiply here though: pext would need cfg(target_feature = "bmi2") (not enabled in default x86_64 builds) or runtime detection plus unsafe, and it is microcoded and much slower on AMD before Zen 3. Since it would only save the shift, the portable version seems the better trade-off.

@viirya
viirya requested a review from alamb November 2, 2026 14:49

@sunchao sunchao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bulk speedup reproduced on x86-64. Appending 65,536 random booleans at bit offset 3 fell from about 272 µs to 3.02 µs. All 380 arrow-buffer unit tests passed locally, and I found no correctness issue with bit ordering or appending after truncation. The inline comment covers a smaller-input performance regression. This review and its benchmark probes were AI-assisted.

let buffer = self.buffer.as_slice_mut();

// Set bits individually until the write position is byte aligned
let head = ((8 - offset % 8) % 8).min(additional);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For slices shorter than eight booleans, no packed byte can be written, but each call still goes through the head and tail setup. I measured consecutive appends into a preallocated builder starting at bit offset 3, cycling the slice length from 1 through 7. On AMD EPYC Milan with rustc 1.97.1 in release mode, random input went from 23.2 to 25.8 ns/call and all-false input from 4.75 to 6.76 ns/call. A local control that used one scalar loop for len < 8 brought those down to about 23 and 5.3 ns/call, respectively. Could we keep a single scalar path for these short slices and add a repeated-short-append case alongside the 64Ki benchmark?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I reproduced this on Apple M-series too. With a new append_slice short bench (7168 appends of 1–7 values starting at bit offset 3), random went from 22.8 to 31.0 µs and all-false from 19.7 to 31.7 µs. A scalar loop for len < 8 on its own only recovered part of it (~24 / ~26 µs). In fae73df I kept the original per-bit loop for len < 8 and moved the packing path into an #[inline(never)] helper. That gives 20.0 / 18.6 µs, slightly faster than main, and the 64Ki cases are unchanged (~1.2 µs vs 75–165 µs on main). The short-append case is now part of the boolean_buffer_builder bench.

Slices of fewer than 8 values cannot fill a packed byte, so the head and
tail setup only added overhead to them. Use the original per-bit loop for
those and move the packing path out of line, so the inlined code for
short appends stays as small as before. Adds a benchmark of repeated
appends of 1 to 7 values.

Co-authored-by: Isaac <[email protected]>
@viirya
viirya requested a review from sunchao November 2, 2026 17:26

@sunchao sunchao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for following up. I reran the original 1–7-value workload on AMD EPYC Milan. Cycling through independent random values now takes 21.9 ns/call versus 22.9 on main, and all-false is back at 4.7 ns/call. The 64Ki random append still takes about 3.0 µs, and all 380 arrow-buffer unit tests passed. I found no correctness issue. The two inline comments cover an adjacent alignment case and the input used by the new benchmark. The review and benchmark probes were AI-assisted.

Comment thread arrow-buffer/src/builder/boolean.rs Outdated
for (i, v) in slice.iter().enumerate() {

// Too short to fill a whole byte, so packing would only add overhead
if additional < 8 {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eight values starting at bit offset 3 still go through pack_slice, but five values fill the head and three fill the tail, leaving zero whole bytes to pack. Repeated eight-value appends preserve that offset. In a preallocated builder on AMD EPYC Milan (rustc 1.97.1, release), all-false went from 5.9 ns/call on main to 10.0 here, and all-true from 11.3 to 14.1. Selecting the scalar loop when no aligned byte fits brought those to 7.0 and 11.1 ns/call. Could you include this boundary in the timing and consider accounting for alignment in the cutoff? The aligned eight-value random case already benefits substantially from packing.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed here too: 8-value all-false appends at offset 3 went from 28–29 µs (7168 calls) on main to 31–35 µs at fae73df. Rather than an alignment-aware cutoff, I took @mbutrovich's register packing suggestion in f00dc8d, so the five head values and three remainder values become two ORs. That case is now 24.6–24.9 µs, and the random one went from 170–178 µs on main (63–68 µs at fae73df) to 24–25 µs. The bench now has 8-value groups at offsets 0 and 3.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for rerunning this on Milan. I can't reproduce the x86 numbers here, but on Apple M4 Max additional <= 8 is also better for every 8-value case, and I don't see the single-element slowdown: 7168 single-value appends take 13.4–13.9 µs with either cutoff (30–31 µs on main). So in d71aaf9 the short register path now takes up to 8 values. With the same bench, 7168 calls, main → this PR:

  • 8 values at offset 3, all false: 27.2 → 16.9 µs
  • 8 values at offset 3, random: 167–169 → 17.1–17.2 µs
  • 8 values at offset 0, all false: 27.1 → 17.4 µs (22 µs with < 8)
  • 8 values at offset 0, random: 168 → 17.4 µs (22 µs with < 8)
  • 1–7 values: unchanged at 18.6 µs (random) and 17.6 µs (all false)

test_append_slice_all_byte_patterns now also appends 16 values, so the multiply path still sees all 256 patterns. Could you check whether the single-element slowdown you saw on Milan still shows up with this version?

builder.append_n(3, true);
for i in 0..CALLS {
let len = i % 7 + 1;
builder.append_slice(hint::black_box(&values[..len]));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The short random case starts at values[0] on every call. Lengths 1 through 7 therefore repeat the same 28 booleans 1,024 times. In a control with identical slice lengths and consecutive memory accesses, that repeating pattern took about 6.7 ns/call, versus 12–14 ns/call with independently generated values. Could you generate CALLS * 4 seeded booleans before timing and advance a cursor through them? That would make the random row in the PR description exercise the workload it describes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would make the random row in the PR description exercise the workload it describes.

On an Apple M5 Max this also changes the size of the gain. In a default release build, the current short/random case takes 19.1 to 19.3 us on main and 16.9 to 17.0 us on this PR, which matches the description's -12%. With fresh values and the same lengths, main takes 55.3 to 55.9 us and this PR takes 25.9 to 27.2 us. Main's time depends on the build (35.3 us with thin LTO). This PR stays at about 26 us with fresh values against 17 us for the repeated pattern in every build I ran. The repeated pattern also hides most of what the register packing suggestion on line 325 saves: 16.9 to 15.2 us on the repeated pattern, and 26 to 16.4 us with fresh values.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. The repeated 28 booleans let main's per-bit branch predict well. In f00dc8d the short group walks a cursor through CALLS * 4 seeded values. With fresh values, short/random is 76–84 µs on main, 33–36 µs at fae73df, and 19–20 µs now. I've updated the description to match.

@mbutrovich mbutrovich left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @viirya! The multiply packing is a big win, and I see the same speedup on an Apple M5 Max.

Comment thread arrow-buffer/src/builder/boolean.rs Outdated
Comment on lines 280 to 325
// Too short to fill a whole byte, so packing would only add overhead
if additional < 8 {
for (i, v) in slice.iter().enumerate() {
if *v {
unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), offset + i) }
}
}
} else {
self.pack_slice(offset, slice)
}
}

/// Writes `slice` into the already allocated bits starting at `offset`
///
/// Kept out of line so that the short slice path of [`Self::append_slice`]
/// stays small when inlined
#[inline(never)]
fn pack_slice(&mut self, offset: usize, slice: &[bool]) {
let additional = slice.len();
let buffer = self.buffer.as_slice_mut();

// Set bits individually until the write position is byte aligned
let head = ((8 - offset % 8) % 8).min(additional);
let (head_slice, rest) = slice.split_at(head);
for (i, v) in head_slice.iter().enumerate() {
if *v {
unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), offset + i) }
bit_util::set_bit(buffer, offset + i)
}
}

// Pack 8 bools into each byte without branching: a `bool` is a byte
// holding 0 or 1, and the multiply moves byte `i` to bit `56 + i`
let byte_offset = (offset + head) / 8;
let (chunks, remainder) = rest.as_chunks::<8>();
for (dst, chunk) in buffer[byte_offset..].iter_mut().zip(chunks) {
let bytes: [u8; 8] = std::array::from_fn(|i| chunk[i] as u8);
let packed = u64::from_le_bytes(bytes).wrapping_mul(0x0102_0408_1020_4080) >> 56;
*dst = packed as u8;
}

let remainder_offset = self.len - remainder.len();
for (i, v) in remainder.iter().enumerate() {
if *v {
bit_util::set_bit(buffer, remainder_offset + i)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we build the head, remainder, and short-slice bits in a register with (*v as u8) << i instead of if *v { set_bit(..) }? Those three loops still branch on every value. In the release build of pack_slice at this commit, the head and remainder loops contain 14 branches on a loaded bool, on both aarch64 (tbz/cbz w9) and x86_64 (cmp byte ptr [rdx + 1], 1 then jne). With the suggestion below, each value is a load and a shifted OR, and the only branches left compare against the length:

ldrb    w9, [x2, #1]
orr     w12, w12, w9, lsl #1    ; value 1 into bit 1
cmp     x10, #2                 ; x10 = head, stop after 2 values
b.eq    LBB40_9

Each region then does one read-modify-write of its byte, and the short path writes at most two bytes. This also covers @sunchao's case of eight values at offset 3 without an alignment-aware cutoff. Its five head values and three remainder values become two writes instead of eight branches.

I measured this with extra cases in boolean_buffer_builder. The 1-to-7 rows are 7168 appends cycling through 1 to 7 values from bit offset 3. The 8-value rows are 7168 appends of 8 values. All rows read consecutive fresh values. These are us per iteration on an Apple M5 Max with thin LTO:

case main this PR suggestion
1 to 7 values, random 35.3 26.3 16.4
1 to 7 values, all false 16.8 16.8 15.6
1 to 7 values, all true 23.9 21.1 15.6
8 values at offset 0, random 93.1 21.7 17.3
8 values at offset 0, all false 24.3 21.1 17.0
8 values at offset 3, random 89.6 45.5 21.0
8 values at offset 3, all false 20.8 25.4 21.1
8 values at offset 3, all true 31.1 31.6 21.2
64Ki, offset 0 or 3, all three inputs 58 to 133 1.05 to 1.08 1.04 to 1.07

The PR and suggestion columns agree within about 1 us in a default release build and in a build with function and block alignment fixed. The cost is in aligned appends, where the head now ORs 0 into the first byte. The offset 0 rows measure that case, and they aren't slower. The suggestion also removes the unsafe call to set_bit_raw.

Suggested change
// Too short to fill a whole byte, so packing would only add overhead
if additional < 8 {
for (i, v) in slice.iter().enumerate() {
if *v {
unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), offset + i) }
}
}
} else {
self.pack_slice(offset, slice)
}
}
/// Writes `slice` into the already allocated bits starting at `offset`
///
/// Kept out of line so that the short slice path of [`Self::append_slice`]
/// stays small when inlined
#[inline(never)]
fn pack_slice(&mut self, offset: usize, slice: &[bool]) {
let additional = slice.len();
let buffer = self.buffer.as_slice_mut();
// Set bits individually until the write position is byte aligned
let head = ((8 - offset % 8) % 8).min(additional);
let (head_slice, rest) = slice.split_at(head);
for (i, v) in head_slice.iter().enumerate() {
if *v {
unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), offset + i) }
bit_util::set_bit(buffer, offset + i)
}
}
// Pack 8 bools into each byte without branching: a `bool` is a byte
// holding 0 or 1, and the multiply moves byte `i` to bit `56 + i`
let byte_offset = (offset + head) / 8;
let (chunks, remainder) = rest.as_chunks::<8>();
for (dst, chunk) in buffer[byte_offset..].iter_mut().zip(chunks) {
let bytes: [u8; 8] = std::array::from_fn(|i| chunk[i] as u8);
let packed = u64::from_le_bytes(bytes).wrapping_mul(0x0102_0408_1020_4080) >> 56;
*dst = packed as u8;
}
let remainder_offset = self.len - remainder.len();
for (i, v) in remainder.iter().enumerate() {
if *v {
bit_util::set_bit(buffer, remainder_offset + i)
}
}
// Too short to fill a whole byte, so packing would only add overhead
if additional < 8 {
if additional == 0 {
return;
}
// At most 7 bits starting at bit 7 end at bit 13, so they span at most two bytes
let bits = (Self::pack_bits(slice) as u16) << (offset % 8);
let buffer = self.buffer.as_slice_mut();
buffer[offset / 8] |= bits as u8;
if let Some(next) = buffer.get_mut(offset / 8 + 1) {
*next |= (bits >> 8) as u8;
}
} else {
self.pack_slice(offset, slice)
}
}
/// Packs up to 7 bools into the low bits of a byte, `slice[i]` at bit `i`,
/// without a branch per value
#[inline]
fn pack_bits(slice: &[bool]) -> u8 {
slice
.iter()
.enumerate()
.fold(0, |acc, (i, v)| acc | ((*v as u8) << i))
}
/// Writes `slice` into the already allocated bits starting at `offset`
///
/// Kept out of line so that the short slice path of [`Self::append_slice`]
/// stays small when inlined
#[inline(never)]
fn pack_slice(&mut self, offset: usize, slice: &[bool]) {
let additional = slice.len();
let buffer = self.buffer.as_slice_mut();
// Fill the first byte up to the next byte boundary
let head = ((8 - offset % 8) % 8).min(additional);
let (head_slice, rest) = slice.split_at(head);
buffer[offset / 8] |= Self::pack_bits(head_slice) << (offset % 8);
// Pack 8 bools into each byte without branching: a `bool` is a byte
// holding 0 or 1, and the multiply moves byte `i` to bit `56 + i`
let byte_offset = (offset + head) / 8;
let (chunks, remainder) = rest.as_chunks::<8>();
for (dst, chunk) in buffer[byte_offset..].iter_mut().zip(chunks) {
let bytes: [u8; 8] = std::array::from_fn(|i| chunk[i] as u8);
let packed = u64::from_le_bytes(bytes).wrapping_mul(0x0102_0408_1020_4080) >> 56;
*dst = packed as u8;
}
// The remainder starts on a byte boundary
if !remainder.is_empty() {
buffer[(self.len - remainder.len()) / 8] |= Self::pack_bits(remainder);
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, applied in f00dc8d, with you as co-author. On Apple M-series, compared with main (fae73df in parentheses):

  • 1–7 values, random: 76–84 → 19–20 µs (33–36)
  • 1–7 values, all false: 22–24 → 18 µs (19–21)
  • 8 values at offset 3, random: 170–178 → 24–25 µs (63–68)
  • 8 values at offset 3, all false: 28–29 → 25 µs (31–35)
  • 8 values at offset 0: 22–23 µs, vs 23–25 at fae73df, so the head OR of 0 doesn't cost anything measurable here

The 64Ki cases are unchanged at about 1.2–1.3 µs. test_append_slice_offsets covers every path (lengths 0..100 at offsets 0..16), and it fails if either the second-byte write in the short path or the head OR is dropped.

});
}

group.finish();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add 8-value appends at offsets 0 and 3 next to the short group? At offset 3 the five head values and three remainder values all go through the per-bit loops and none is packed. That's the case in #12024 (comment). At offset 0 each call packs one byte and has no head. That's the case where the register packing suggestion on line 325 gains least, because its head ORs 0 into the first byte. With both cases here, the benchmark bot would show whether either one regresses.

Suggested change
group.finish();
group.finish();
// Many appends of 8 values each. At offset 3 every value goes to the head
// or the remainder, and none is packed.
let eight_inputs = [
(
"random",
(0..CALLS * 8).map(|_| rng.random_bool(0.5)).collect(),
),
("all_false", vec![false; CALLS * 8]),
];
let mut group = c.benchmark_group("BooleanBufferBuilder append_slice eight");
group.throughput(Throughput::Elements(CALLS as u64));
for (name, values) in &eight_inputs {
for offset in [0, 3] {
let id = BenchmarkId::new(format!("offset_{offset}"), name);
group.bench_with_input(id, values, |b, values: &Vec<bool>| {
b.iter(|| {
let mut builder = BooleanBufferBuilder::new(offset + values.len());
builder.append_n(offset, true);
for chunk in values.as_chunks::<8>().0 {
builder.append_slice(hint::black_box(chunk));
}
hint::black_box(builder.finish())
})
});
}
}
group.finish();

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added as suggested in f00dc8d.

The head, remainder and short slice loops still branched on every value.
Build their bits with `(v as u8) << i` instead and write each byte once,
which also covers 8-value appends at an unaligned offset, where nothing
is packed with the multiply, and removes the `set_bit_raw` call.

The short benchmark now reads fresh values instead of repeating the same
28 booleans, and a new group appends 8 values at offsets 0 and 3.

Co-authored-by: Matt Butrovich <[email protected]>
Co-authored-by: Isaac <[email protected]>

@mbutrovich mbutrovich left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @viirya, LGTM now!

@viirya
viirya requested a review from sunchao November 2, 2026 20:21

@sunchao sunchao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The short benchmark now consumes consecutive seeded values, which addresses my benchmark comment. I also found no correctness issue in the revised packing. All 380 arrow-buffer unit tests passed locally.

I reran the PR's new eight-value benchmark on AMD EPYC Milan with rustc 1.97.1. These are the times for 7,168 appends at bit offset 3, using the same benchmark on both revisions. The ranges span the point estimates from two runs.

Input main f00dc8d
Random 252–261 µs 71–74 µs
All false 42–44 µs 69–71 µs

The random case is substantially faster. The all-false slowdown from the earlier alignment discussion still reproduces on Milan. As a control, allowing the short register path to handle exactly eight values (additional <= 8) brought both rows to about 44 µs. That cutoff also made single-element calls slower in a separate probe, so there is a tradeoff worth weighing alongside the Apple results.

This review and its benchmark probes were AI-assisted.

… path

Eight values at an unaligned offset fill the head and remainder and
leave no whole byte to pack, but still went through pack_slice. Up to 8
values touch at most two bytes, so let the short register path take
them. test_append_slice_all_byte_patterns now also appends 16 values,
so every pattern still goes through the multiply.

Co-authored-by: Isaac <[email protected]>
@viirya
viirya requested a review from sunchao November 4, 2026 01:21
@viirya

viirya commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

@sunchao Can you take another look? Thanks!

@sunchao sunchao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reran the original single-element probe on AMD EPYC Milan with rustc 1.97.1. The approximately 2 ns slowdown I mentioned in my previous review did not reproduce. With the length supplied at runtime, both f00dc8d and d71aaf9 took about 3.4 ns/call for random and all-false input across two counterbalanced runs. For comparison, main took 6.3 ns for random and 2.3 ns for all-false input.

The eight-value cutoff fixes my earlier offset-3 concern. For 7,168 all-false appends, the PR's Criterion benchmark took 43.6–44.0 µs on d71aaf9, 68.7–69.2 µs on f00dc8d, and 42.8–43.7 µs on main. Random input took 43.6–44.1 µs on this revision versus about 249 µs on main. All 380 arrow-buffer unit tests passed, including the extended byte-pattern test. My only remaining note is a stale benchmark comment.

This review and its benchmark probes were AI-assisted.

Comment on lines +89 to +90
// Many appends of 8 values each. At offset 3 every value goes to the head
// or the remainder, and none is packed.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small wording update for the new cutoff. Both offsets now pack all eight values through the short path. The distinction this benchmark captures is how many destination bytes are written.

Suggested change
// Many appends of 8 values each. At offset 3 every value goes to the head
// or the remainder, and none is packed.
// Repeated eight-value appends write one byte at offset 0 and span two bytes at offset 3.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, updated in 9ae347f.

// Up to 8 values touch at most two bytes, so pack them directly. This
// includes 8 values at an unaligned offset, which leave no whole byte
// for `pack_slice` to pack.
if additional <= 8 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems like a reasonable plan to me

I am curious if you tried larger sizes (like back 64 bits at a time, for example)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried two versions of that on Apple M4 Max, against the same bench (7168 calls per case unless noted):

  • Widening the register path to a u64, so slices of up to 57 values skip pack_slice: 1–8 values got about 40% slower (17–18 → 24–27 µs), and 7168 appends of 9–57 values went from 58 → 69 µs. The fold over 57 values is a serial shift/OR chain, while pack_slice does one multiply per 8 values.
  • Packing 64 bools into a u64 and storing it whole in pack_slice: 64Ki values went from 1.21–1.27 → 1.28–1.32 µs. The current loop already compiles to an unrolled multiply-and-store with no bounds checks, so combining the bytes only adds shifts and ORs.

So I kept the 8-value cutoff and the byte-at-a-time loop.

}
// At most 8 bits starting at bit 7 end at bit 14, so they span at most two bytes
let bits = (Self::pack_bits(slice) as u16) << (offset % 8);
let buffer = self.buffer.as_slice_mut();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could probably avoid a bounds check here with some unsafe

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, get_unchecked_mut works here since advance has already grown the buffer to hold bit offset. On Apple M4 Max it saved up to about 5% on 8-value appends at offset 3 (18.3 → 17.4 µs) and 1–2% on the 1–7 value case; the other cases were within noise. Given that, I'd rather keep this path free of unsafe, but I'm happy to add it if you think it's worth it.

@viirya
viirya added this pull request to the merge queue Nov 6, 2026
@viirya

viirya commented Nov 6, 2026 •

Copy link
Copy Markdown
Member Author

Thanks all for reviewing this.

Merged via the queue into apache:main with commit bb47f80 Nov 6, 2026
23 checks passed
@Jefffrey Jefffrey added performance Speed or memory optimizations and removed enhancement New feature/addition labels Nov 6, 2026
@viirya
viirya deleted the boolean-append-slice-branchless branch November 6, 2026 17:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arrow-core Core crates related to representing arrow data performance Speed or memory optimizations

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BooleanBufferBuilder::append_slice sets one bit at a time, making it a bottleneck when reading Parquet BOOLEAN columns

6 participants