Skip to content

perf(arrow-buffer): append boolean slices more efficiently - #12042

Closed
waynexia wants to merge 2 commits into
apache:mainfrom
waynexia:perf/boolean-append-slice
Closed

waynexia wants to merge 2 commits into
apache:mainfrom
waynexia:perf/boolean-append-slice

Conversation

@waynexia

@waynexia waynexia commented Nov 3, 2026

Copy link
Copy Markdown
Member

Which issue does this PR close?

  • N/A

Rationale for this change

BooleanBufferBuilder::append_slice (which also backs BooleanBuilder::append_slice, NullBufferBuilder::append_slice, PrimitiveBuilder::append_values, and BooleanBuffer::from(&[bool])) previously appended booleans one bit at a time:

for (i, v) in slice.iter().enumerate() {
    if *v {
        unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), offset + i) }
    }
}

This had two main performance bottlenecks:

  1. Branch mispredictions: Every element required a conditional branch (if *v), causing frequent branch mispredictions on unpredictable boolean inputs.
  2. Repeated byte-level read-modify-writes: set_bit_raw performs a byte read, bitwise OR, and store for every true bit, creating a store-to-load dependency chain on the same target byte up to 8 times.

Packing 8 booleans at a time into a single byte without branches and storing whole bytes eliminates both the branch mispredictions and the per-bit read-modify-write traffic.

Human Rationale

I'm trying to find something to burn my token, and come across this. This PR is fully written by AI. I have read and understand all logic changes. It increases complexity, but given that this part is not likely to be touched too often, I thought it was acceptable.

What changes are included in this PR?

  • Refactor BooleanBufferBuilder::append_slice into three phases:
    1. Head: If the current bit offset is not byte-aligned, pack the leading booleans into the existing partial byte while preserving already-written low bits and zeroing upper padding bits.
    2. Middle: Process 8 booleans at a time (as_chunks::<8>()) using a branchless SWAR multiplication ((u64::from_le_bytes(bytes).wrapping_mul(0x0102_0408_1020_4080) >> 56) as u8) and write full bytes directly to the buffer. wrapping_mul(0x0102_0408_1020_4080) >> 56) equals to 8 continuous "shift-left + OR"
    3. Tail: Pack any remaining < 8 booleans into the final byte, keeping the trailing padding bits zeroed.
  • Add unit tests in arrow-buffer covering unaligned head/tail combinations, all-true/all-false inputs, empty slices, zeroed padding invariants, and randomized comparisons against a reference bit-by-bit implementation.

Are these changes tested?

Yes

Performance can also be verified with the existing bench_bool benchmark in arrow/benches/builder.rs (cargo bench -p arrow --bench builder -- bench_bool).

On my local env, depends on the scenario, this patch can achieve at least 5x improvement on microbenchmark, except one bad case that append 1 bit a time

Are there any significant user-facing changes?

No.

…at a time

`append_slice` appended one bit at a time, doing a byte-level
read-modify-write and an unpredictable branch for every boolean. Pack 8
booleans into a byte with a multiplication and a constant shift, and
store whole bytes; only the partial byte at the head and the trailing
partial byte need per-bit bookkeeping. `len` is still advanced up front,
so the bookkeeping is unchanged, and the padding bits above the final
bit stay zero.

Adds tests for unaligned head/tail bytes, all-true/all-false slices,
empty slices, zeroed padding, and a randomized comparison against a
bit-by-bit reference.
Signed-off-by: Ruihang Xia <[email protected]>
@github-actions github-actions Bot added the arrow-core Core crates related to representing arrow data label Nov 3, 2026
@Rich-T-kid

Copy link
Copy Markdown
Contributor

run benchmark builder
env:
BENCH_FILTER: bench_bool

1 similar comment
@Rich-T-kid

Copy link
Copy Markdown
Contributor

run benchmark builder
env:
BENCH_FILTER: bench_bool

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark starting (GKE) | trigger

Target: builder

Sharding factor: 1 (1 workers).

Comparing perf/boolean-append-slice (fffeec0) to 9ffd63d (merge-base) diff

Run configuration
run benchmark builder
env:
  BENCH_FILTER: bench_bool
shards: 1

Results will be posted when all workers finish.


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark starting (GKE) | trigger

Target: builder

Sharding factor: 1 (1 workers).

Comparing perf/boolean-append-slice (fffeec0) to 9ffd63d (merge-base) diff

Run configuration
run benchmark builder
env:
  BENCH_FILTER: bench_bool
shards: 1

Results will be posted when all workers finish.


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark failed or incomplete (GKE) | trigger

Target: builder

Comparing perf/boolean-append-slice (fffeec0) to 9ffd63d (merge-base) diff

Run configuration
run benchmark builder
env:
  BENCH_FILTER: bench_bool
shards: 1
Errors / missing shards
builder — shard 1/1: Benchmark for [this request](https://github.com/apache/arrow-rs/pull/12042#issuecomment-6595232801) failed before finishing (Kubernetes reason: `BackoffLimitExceeded`).

Benchmarks requested: `builder`

<details><summary>Kubernetes message</summary>

```
Job has reached the specified backoff limit
```

</details>

---
[File an issue](https://github.com/adriangb/datafusion-benchmarking/issues) against this benchmark runner
Per-runner information
builder — shard 1/1

Runner information unavailable.


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark completed (GKE) | trigger

Target: builder

Comparing perf/boolean-append-slice (fffeec0) to 9ffd63d (merge-base) diff

Run configuration
run benchmark builder
env:
  BENCH_FILTER: bench_bool
shards: 1
Details
group                    base                                   changed
-----                    ----                                   -------
bench_bool/bench_bool    8.73    298.4±0.47µs  1675.6 MB/sec    1.00     34.2±0.02µs    14.3 GB/sec

Per-runner information
builder — shard 1/1

Node: gk3-benchmark-cluster-nap-17yz8u0s-c78dad10-gvbd

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

uname:

Linux bench-c6595232042-4295-jlz2k 6.12.105+ #1 SMP Sat Sep 19 07:55:25 UTC 2026 aarch64 GNU/Linux

BENCH_COMMAND:

cargo bench --features=arrow,async,test_common,experimental,object_store --bench builder
CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Resource Usage

base (merge-base)

Metric Value
Wall time 15.0s
Peak memory 4.4 MiB
Avg memory 3.2 MiB
CPU user 10.7s
CPU sys 0.0s
Peak spill 0 B

branch

Metric Value
Wall time 15.0s
Peak memory 8.5 MiB
Avg memory 3.0 MiB
CPU user 9.0s
CPU sys 0.0s
Peak spill 0 B

File an issue against this benchmark runner

@Rich-T-kid

Copy link
Copy Markdown
Contributor

run benchmark builder
env:
BENCH_FILTER: bench_bool

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark starting (GKE) | trigger

Target: builder

Sharding factor: 1 (1 workers).

Comparing perf/boolean-append-slice (fffeec0) to 9ffd63d (merge-base) diff

Run configuration
run benchmark builder
env:
  BENCH_FILTER: bench_bool
shards: 1

Results will be posted when all workers finish.


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark completed (GKE) | trigger

Target: builder

Comparing perf/boolean-append-slice (fffeec0) to 9ffd63d (merge-base) diff

Run configuration
run benchmark builder
env:
  BENCH_FILTER: bench_bool
shards: 1
Details
group                    base                                   changed
-----                    ----                                   -------
bench_bool/bench_bool    8.62    294.5±0.52µs  1697.8 MB/sec    1.00     34.2±0.01µs    14.3 GB/sec

Per-runner information
builder — shard 1/1

Node: gk3-benchmark-cluster-nap-1embnon5-4daa0a8c-89kl

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

uname:

Linux bench-c6622256434-4432-5jpqk 6.12.105+ #1 SMP Sat Sep 19 07:55:25 UTC 2026 aarch64 GNU/Linux

BENCH_COMMAND:

cargo bench --features=arrow,async,test_common,experimental,object_store --bench builder
CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Resource Usage

base (merge-base)

Metric Value
Wall time 15.0s
Peak memory 4.4 MiB
Avg memory 3.2 MiB
CPU user 10.4s
CPU sys 0.0s
Peak spill 0 B

branch

Metric Value
Wall time 15.0s
Peak memory 8.3 MiB
Avg memory 2.9 MiB
CPU user 9.0s
CPU sys 0.0s
Peak spill 0 B

File an issue against this benchmark runner

@alamb

alamb commented Nov 4, 2026

Copy link
Copy Markdown
Contributor
Screenshot 2026-11-04 at 4 18 38 PM

🚀

@Rich-T-kid

Copy link
Copy Markdown
Contributor

@waynexia could you rebase this PR, i'm interested in reviewing it

@mbutrovich

Copy link
Copy Markdown
Contributor

Isn't this redundant to #12024 that already merged?

@Rich-T-kid

Copy link
Copy Markdown
Contributor

it seems that way, we need to rebase and re-run the benchmarks

@Rich-T-kid Rich-T-kid 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.

can we re-base this Pr and re-run the benchmarks @waynexia

@mbutrovich

mbutrovich commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

I mean, do we even need to do that? I read the code. It’s doing the same thing.

Maybe the author can explain how it’s different before we burn more reviewer cycles and benchmarking infrastructure.

@waynexia

Copy link
Copy Markdown
Member Author

Ahh, I rebased this branch against the latest main and ... all code diffs are gone. I read #12024 and yes, they are very identical 🤣 Apologize for this, I haven't checked the PR list when opening this one 🙈 I'll be more careful next time scanning for optimizations. Closing this ticket

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.

5 participants