Skip to content

perf: Optimize array_sort to count validity bits while compacting - #26453

Merged
neilconway merged 4 commits into
apache:mainfrom
neilconway:neilc/array-sort-count-while-compacting
Oct 22, 2026
Merged

neilconway merged 4 commits into
apache:mainfrom
neilconway:neilc/array-sort-count-while-compacting

Conversation

@neilconway

@neilconway neilconway commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

  • N/A

Rationale for this change

This PR optimizes array_sort on arrays of primitive values, where at least one element in the batch is NULL.

Previously, array_sort started by counting the NULL elements in the row and then compacting the non-NULL elements to place NULLs either first or last (depending on the specified sort order). Doing the compaction already requires looking at every element's validity bit, so we can make this more efficient by doing the compaction first and deriving the null count as we go. When NULLS FIRST, we then need to move the non-NULL values after the NULLs. Empirically, the cost of the move is outweighed by the savings from avoiding a separate null count.

The compaction loop avoids branching on each element's validity bit: when NULLs are scattered through a row, the CPU frequently mispredicts that branch. Instead, write every value to the next output slot and advance the write position only on valid values (which we can do without a branch!). Per suggestion by @mbutrovich.

One consequence of the previous approach is that values in NULL slots were always the zeroed. We don't attempt to preserve that behavior, because Arrow allows NULL slots to contain arbitrary values.

Two alternatives were considered:

  1. Using SetBitCounter from perf: Optimize array_filter #25754; this was faster on some inputs and slower on others.
  2. Compacting values at the end of the buffer for NULLS FIRST, walking elements backwards but avoiding the post-compaction move; this was faster for small rows and slower for large rows.

Along the way, improve the array_sort benchmarks:

  1. Add coverage for NULLS LAST
  2. Cycle through several input arrays and make the distribution of NULLs and array lengths more unpredictable, to avoid the branch predictor being able to memorize the benchmark input.

Benchmarks

x86, AMD EPYC-Milan:

  int32_null_elements/5                -24.3%
  int32_null_elements/20               -19.5%
  int32_null_elements/100              -13.1%
  int32_null_elements/1000              -8.9%
  int32_null_elements_desc/5           -24.3%
  int32_null_elements_desc/20          -19.1%
  int32_null_elements_desc/100         -13.6%
  int32_null_elements_desc/1000         -9.1%
  int32_null_elements_nulls_last/5     -28.4%
  int32_null_elements_nulls_last/20    -21.1%
  int32_null_elements_nulls_last/100   -14.6%
  int32_null_elements_nulls_last/1000   -9.4%

What changes are included in this PR?

See above.

What is the testing strategy for this PR?

Existing tests pass, new tests added.

Are there any user-facing changes?

No.

The cases with NULL elements all put the NULLs first, which is the
default. Add int32_null_elements_nulls_last, which sorts the same lists
with NULLS LAST.

Every case sorted the same array on every iteration, with exactly N
elements per row and a NULL at every 10th element or row. A query sorts
each batch once, but a benchmark that repeats one input lets the CPU's
branch predictor learn its branch outcomes: in arrow-rs's zip
benchmarks, AMD EPYC Milan learned repeated sequences of 32Ki to 64Ki
outcomes, and an array with 5 elements per row has 40Ki elements. Fixed
row lengths and evenly spaced NULLs are easy to predict even without
repetition. Now:

- Each case cycles through arrays built from different seeds, one per
  iteration: at least two, and together at least 1Mi elements (26
  arrays at 5 elements per row, 7 at 20, 3 at 50, and 2 at 100 and
  1000).
- Row lengths are random, from 1 to 2N - 1, so N in a case's name is
  now the average length.
- NULL elements and NULL rows are at random positions, 10% of each.

Results from before this change are not comparable with results after
it.
sort_rows_with_nulls needs each row's NULL count to place the NULLs and
to bound the sort. It got that count by slicing the element null buffer
for each row, which clones a reference-counted buffer and runs a
separate bit count. The loop that compacts a row's valid values already
reads every element's validity bit, so count the valid values there.
The values are compacted to the start of the row's output region and
sorted there; with NULLS FIRST, rows that contain NULLs then move the
sorted values after the NULLs. The validity bits are read with
BitIterator, which checks bounds once per row rather than once per
element.

Two alternatives were measured on x86 with the benchmark as it was
before the previous commit. Counting with SetBitCounter made 20-element
rows up to 7% slower than main, while 5-element rows were 16-22% faster:
Rust's default x86-64 target has no popcnt instruction, so each count is
a sequence of about 15 instructions, and they sat in the same loop as
the inlined insertion sort used for short rows. Filling NULLS FIRST rows
from the end avoids the move and was faster for short rows (-34% at 5
elements), but walking long rows backwards was 2-7% slower than main at
1000 elements per row on three servers, even with a loop that matched
the forward one instruction for instruction.

x86 (AMD EPYC-Milan, Hetzner ccx33), against the previous commit,
fastest of 3 alternating rounds:

  int32_null_elements/5                -15.4%
  int32_null_elements/20                -4.6%
  int32_null_elements/100               -5.6%
  int32_null_elements/1000              +1.0%
  int32_null_elements_desc/5           -16.5%
  int32_null_elements_desc/20           -6.8%
  int32_null_elements_desc/100          -3.5%
  int32_null_elements_desc/1000         -0.2%
  int32_null_elements_nulls_last/5     -20.7%
  int32_null_elements_nulls_last/20     -7.7%
  int32_null_elements_nulls_last/100    -6.7%
  int32_null_elements_nulls_last/1000   -2.0%

The cases that do not reach this code (no NULL elements, NULL rows only,
and strings) moved by -2.0% to +4.5% in the same run, so the
1000-element results are within noise.
@neilconway neilconway changed the title perf: Optimize array_sort to count bits while compacting perf: Optimize array_sort to count validity bits while compacting Oct 17, 2026
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.11321% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 82.89%. Comparing base (484183d) to head (3a38583).

Files with missing lines Patch % Lines
datafusion/functions-nested/src/sort.rs 98.11% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #26453      +/-   ##
==========================================
- Coverage   82.89%   82.89%   -0.01%     
==========================================
  Files        1154     1154              
  Lines      457630   457673      +43     
  Branches   457630   457673      +43     
==========================================
+ Hits       379370   379402      +32     
- Misses      55256    55261       +5     
- Partials    23004    23010       +6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@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 @neilconway! Counting while compacting is a nice simplification, and the randomized benchmark inputs make these numbers more trustworthy than the old fixed null pattern.

Comment on lines +346 to +354
let mut write_pos = out_start;
for (&value, is_valid) in src_values[start..end].iter().zip(validity_bits) {
if is_valid {
out_values[write_pos] = value;
write_pos += 1;
}
}
let valid_count = write_pos - out_start;
let null_count = row_len - valid_count;

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.

What do you think about making this loop branchless? It currently branches on every validity bit. With the benchmark's random NULLs (10% of elements), that branch is hard to predict. If we write every value and advance write_pos only past valid ones, the branch goes away.

Here is the loop body for sort_rows_with_nulls::<i32, i32> at this commit and with the suggestion below, built with the workspace release profile (LTO, one codegen unit).

aarch64, this commit:

    lsr   x13, x10, #3
    ldrb  w13, [x9, x13]       ; load the validity byte
    and   x14, x10, #0x7
    lsr   w13, w13, w14
    tbz   w13, #0, LBB239_50   ; branch on the validity bit
    cmp   x27, x20             ; bounds check on out_values
    b.hs  LBB239_111
    ldr   w13, [x11]
    ldr   x14, [sp, #120]
    str   w13, [x14, x27, lsl #2]
    add   x27, x27, #1
    b     LBB239_50

aarch64, suggestion:

    cmp   x21, x20             ; bounds check on out_values
    b.hs  LBB239_113
    ldr   w13, [x12], #4
    lsr   x14, x10, #3
    ldrb  w14, [x9, x14]       ; load the validity byte
    and   x15, x10, #0x7
    lsr   x14, x14, x15
    and   x14, x14, #0x1       ; validity bit as 0 or 1
    add   x10, x10, #1
    ldr   x15, [sp, #136]
    str   w13, [x15, x21, lsl #2]
    add   x21, x21, x14        ; write_pos += is_valid

On x86_64 (--target x86_64-apple-darwin), the branch at this commit is bt edi, r8d followed by jae LBB1005_49. With the suggestion it becomes bt edi, r8d followed by adc rbx, 0.

I ran the int32_null_elements cases on an Apple M5 Max, comparing this commit with the suggestion back to back:

case this PR suggestion change
int32_null_elements/5 257.1 us 253.1 us -1.8%
int32_null_elements_desc/5 264.4 us 258.8 us -2.2%
int32_null_elements_nulls_last/5 237.9 us 234.7 us -0.3%
int32_null_elements/20 796.4 us 711.9 us -12.5%
int32_null_elements_desc/20 834.3 us 739.7 us -13.0%
int32_null_elements_nulls_last/20 755.3 us 659.8 us -12.2%
int32_null_elements/100 3.762 ms 3.459 ms -8.0%
int32_null_elements_desc/100 3.800 ms 3.407 ms -10.3%
int32_null_elements_nulls_last/100 3.674 ms 3.247 ms -11.6%
int32_null_elements/1000 44.60 ms 40.34 ms -9.6%
int32_null_elements_desc/1000 45.93 ms 40.65 ms -11.5%
int32_null_elements_nulls_last/1000 44.39 ms 40.99 ms -7.7%

I haven't measured x86_64. Could you run it on your EPYC machine?

The loop can leave the last NULL's value in the slot right after the valid values. The suggestion resets that slot, so NULL slots stay zeroed the way the NULLS FIRST branch keeps them.

Suggested change
let mut write_pos = out_start;
for (&value, is_valid) in src_values[start..end].iter().zip(validity_bits) {
if is_valid {
out_values[write_pos] = value;
write_pos += 1;
}
}
let valid_count = write_pos - out_start;
let null_count = row_len - valid_count;
// Write every value but advance only past valid ones, so the loop
// doesn't branch on the validity bit.
let mut write_pos = out_start;
for (&value, is_valid) in src_values[start..end].iter().zip(validity_bits) {
out_values[write_pos] = value;
write_pos += is_valid as usize;
}
let valid_count = write_pos - out_start;
let null_count = row_len - valid_count;
// The slot after the valid values can hold a NULL's value. Reset it
// like the other NULL slots.
if null_count > 0 {
out_values[write_pos] = N::default();
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion! Seems promising; I'm running a benchmark now on x86.

The loop can leave the last NULL's value in the slot right after the valid values. The suggestion resets that slot, so NULL slots stay zeroed the way the NULLS FIRST branch keeps them.

On reflection, why don't we just avoid making all NULL slots contain N::default() to begin with, and let them hold whatever they would otherwise hold? It saves a few cycles, and is probably net more readable (less code and no need to explain what's happening in the special-case).

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.

On reflection, why don't we just avoid making all NULL slots contain N::default() to begin with, and let them hold whatever they would otherwise hold? It saves a few cycles, and is probably net more readable (less code and no need to explain what's happening in the special-case).

Sounds reasonable to me!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

x86, branch vs. branchless, with the NULL-slot-fill logic already removed:

case                                                branch  branchless  change
array_sort/int32/5                                 265.820     265.530   -0.1%   (control)
array_sort/int32/1000                            70780.000   71415.000   +0.9%   (control)
array_sort/int32_with_nulls                       2177.800    2172.300   -0.3%   (control)
array_sort/int32_null_elements/5                   406.480     384.300   -5.5%
array_sort/int32_null_elements_desc/5              416.660     396.840   -4.8%
array_sort/int32_null_elements_nulls_last/5        387.190     368.940   -4.7%
array_sort/int32_null_elements/20                 1291.500    1157.300  -10.4%
array_sort/int32_null_elements_desc/20            1342.800    1209.000  -10.0%
array_sort/int32_null_elements_nulls_last/20      1270.300    1131.400  -10.9%
array_sort/int32_null_elements/100                6078.400    5500.600   -9.5%
array_sort/int32_null_elements_desc/100           6222.500    5624.600   -9.6%
array_sort/int32_null_elements_nulls_last/100     6049.500    5467.700   -9.6%
array_sort/int32_null_elements/1000              73921.000   68853.000   -6.9%
array_sort/int32_null_elements_desc/1000         74745.000   69838.000   -6.6%
array_sort/int32_null_elements_nulls_last/1000   73720.000   68953.000   -6.5%

So branchless seems like a clear win. Thanks for the suggestion!

sort_rows_with_nulls compacts each row's valid values to the start of the
row's output region. The compaction loop branched on each element's
validity bit, and the CPU mispredicts that branch often when NULLs are
scattered through the row. The loop now writes every value to the next
output slot and advances the write position only past valid values, so
the next valid value overwrites each NULL's value.

This can leave a NULL's value in a NULL slot of the output. Arrow does
not define what NULL slots hold, so sort_rows_with_nulls no longer resets
any NULL slots, including the ones that the NULLS FIRST move leaves
behind.

x86 (AMD EPYC-Milan, Hetzner ccx33), fastest of 2 alternating rounds,
against the previous commit with its NULL-slot resets removed:

  int32_null_elements/5                 -5.5%
  int32_null_elements/20               -10.4%
  int32_null_elements/100               -9.5%
  int32_null_elements/1000              -6.9%
  int32_null_elements_desc/5            -4.8%
  int32_null_elements_desc/20          -10.0%
  int32_null_elements_desc/100          -9.6%
  int32_null_elements_desc/1000         -6.6%
  int32_null_elements_nulls_last/5      -4.7%
  int32_null_elements_nulls_last/20    -10.9%
  int32_null_elements_nulls_last/100    -9.6%
  int32_null_elements_nulls_last/1000   -6.5%

The cases that do not reach this code (int32/5, int32/1000 and
int32_with_nulls) moved by -0.3% to +0.9% in the same run.
@github-actions github-actions Bot added the functions Changes to functions implementation label Oct 21, 2026
@mbutrovich
mbutrovich self-requested a review October 21, 2026 20:48

@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 @neilconway! The branchless compaction and the x86 numbers look good to me.

@neilconway
neilconway added this pull request to the merge queue Oct 22, 2026
Merged via the queue into apache:main with commit 83d2e9d Oct 22, 2026
44 checks passed
@neilconway
neilconway deleted the neilc/array-sort-count-while-compacting branch October 22, 2026 01:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

functions Changes to functions implementation v56.0.0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants