This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git


The following commit(s) were added to refs/heads/main by this push:
     new bb47f8091e perf(arrow-buffer): pack bools branchlessly in 
`BooleanBufferBuilder::append_slice` (#12024)
bb47f8091e is described below

commit bb47f8091e5ac83117ce95942443e9bf391f2af1
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Fri Nov 6 08:20:07 2026 +0000

    perf(arrow-buffer): pack bools branchlessly in 
`BooleanBufferBuilder::append_slice` (#12024)
    
    # Which issue does this PR close?
    
    - Closes #12023
    
    # 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.
    
    ---------
    
    Co-authored-by: Isaac <[email protected]>
    Co-authored-by: Matt Butrovich <[email protected]>
---
 arrow-buffer/Cargo.toml                        |   4 +
 arrow-buffer/benches/boolean_buffer_builder.rs | 109 +++++++++++++++++++++++++
 arrow-buffer/src/builder/boolean.rs            | 103 ++++++++++++++++++++++-
 3 files changed, 213 insertions(+), 3 deletions(-)

diff --git a/arrow-buffer/Cargo.toml b/arrow-buffer/Cargo.toml
index e63c42dd58..3fcea6799d 100644
--- a/arrow-buffer/Cargo.toml
+++ b/arrow-buffer/Cargo.toml
@@ -63,5 +63,9 @@ harness = false
 name = "null_buffer_builder"
 harness = false
 
+[[bench]]
+name = "boolean_buffer_builder"
+harness = false
+
 [lints]
 workspace = true
diff --git a/arrow-buffer/benches/boolean_buffer_builder.rs 
b/arrow-buffer/benches/boolean_buffer_builder.rs
new file mode 100644
index 0000000000..62b14728bb
--- /dev/null
+++ b/arrow-buffer/benches/boolean_buffer_builder.rs
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+use arrow_buffer::BooleanBufferBuilder;
+use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, 
criterion_main};
+use rand::rngs::StdRng;
+use rand::{RngExt, SeedableRng};
+use std::hint;
+
+const LEN: usize = 64 * 1024;
+
+fn criterion_benchmark(c: &mut Criterion) {
+    let mut rng = StdRng::seed_from_u64(42);
+    let inputs = [
+        ("random", (0..LEN).map(|_| rng.random_bool(0.5)).collect()),
+        (
+            "mostly_true",
+            (0..LEN).map(|_| rng.random_bool(0.9)).collect(),
+        ),
+        ("all_true", vec![true; LEN]),
+    ];
+
+    let mut group = c.benchmark_group("BooleanBufferBuilder append_slice");
+    group.throughput(Throughput::Elements(LEN as u64));
+
+    for (name, values) in &inputs {
+        // An offset of 3 bits makes the slice start in the middle of a byte
+        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 + LEN);
+                    builder.append_n(offset, true);
+                    builder.append_slice(hint::black_box(values));
+                    hint::black_box(builder.finish())
+                })
+            });
+        }
+    }
+
+    group.finish();
+
+    // Many appends of 1 to 7 values each, starting in the middle of a byte.
+    // Lengths cycle through 1 to 7, which adds up to `CALLS * 4` values.
+    const CALLS: usize = 7 * 1024;
+    let short_inputs = [
+        (
+            "random",
+            (0..CALLS * 4).map(|_| rng.random_bool(0.5)).collect(),
+        ),
+        ("all_false", vec![false; CALLS * 4]),
+    ];
+
+    let mut group = c.benchmark_group("BooleanBufferBuilder append_slice 
short");
+    group.throughput(Throughput::Elements(CALLS as u64));
+
+    for (name, values) in &short_inputs {
+        group.bench_with_input(*name, values, |b, values: &Vec<bool>| {
+            b.iter(|| {
+                let mut builder = BooleanBufferBuilder::new(3 + values.len());
+                builder.append_n(3, true);
+                let mut start = 0;
+                for i in 0..CALLS {
+                    let end = start + i % 7 + 1;
+                    builder.append_slice(hint::black_box(&values[start..end]));
+                    start = end;
+                }
+                hint::black_box(builder.finish())
+            })
+        });
+    }
+
+    group.finish();
+
+    // Many appends of 8 values each. Each append writes one byte at offset 0
+    // and spans two bytes at offset 3.
+    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();
+}
+
+criterion_group!(benches, criterion_benchmark);
+criterion_main!(benches);
diff --git a/arrow-buffer/src/builder/boolean.rs 
b/arrow-buffer/src/builder/boolean.rs
index 2982753076..ece7df8ab9 100644
--- a/arrow-buffer/src/builder/boolean.rs
+++ b/arrow-buffer/src/builder/boolean.rs
@@ -263,10 +263,63 @@ impl BooleanBufferBuilder {
         self.advance(additional);
 
         let offset = self.len() - additional;
-        for (i, v) in slice.iter().enumerate() {
-            if *v {
-                unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), 
offset + i) }
+
+        // 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 {
+            if additional == 0 {
+                return;
+            }
+            // 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();
+            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 8 bools into 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);
         }
     }
 
@@ -777,4 +830,48 @@ mod tests {
             }
         }
     }
+
+    #[test]
+    fn test_append_slice_all_byte_patterns() {
+        for byte in 0..=u8::MAX {
+            // 8 values take the short path, 16 values are packed with the 
multiply
+            let values: Vec<bool> = (0..16).map(|i| byte & (1 << (i % 8)) != 
0).collect();
+            let mut b = BooleanBufferBuilder::new(8);
+            b.append_slice(&values[..8]);
+            assert_eq!(b.as_slice(), &[byte]);
+
+            let mut b = BooleanBufferBuilder::new(16);
+            b.append_slice(&values);
+            assert_eq!(b.as_slice(), &[byte, byte]);
+        }
+    }
+
+    #[test]
+    fn test_append_slice_offsets() {
+        // Exercise every combination of starting bit offset and slice length
+        // around the byte boundaries, including after a truncate.
+        let pattern: Vec<bool> = (0..100).map(|i| (i * 7 + i / 3) % 5 < 
2).collect();
+        for start in 0..17 {
+            for len in 0..pattern.len() {
+                let mut b = BooleanBufferBuilder::new(0);
+                b.append_n(start + 3, true);
+                b.truncate(start);
+                b.append_slice(&pattern[..len]);
+                b.append(true);
+                let finished = b.finish();
+                assert_eq!(finished.len(), start + len + 1);
+                for i in 0..start {
+                    assert!(finished.value(i), "start {start} len {len} index 
{i}");
+                }
+                for (i, v) in pattern[..len].iter().enumerate() {
+                    assert_eq!(
+                        finished.value(start + i),
+                        *v,
+                        "start {start} len {len} index {i}"
+                    );
+                }
+                assert!(finished.value(start + len));
+            }
+        }
+    }
 }

Reply via email to