Skip to content

Commit ee0376c

Browse files
committed
Split branches in heapsort child selection
This allows even better code-gen, cmp + adc. While also more clearly communicating the intent.
1 parent 7e07219 commit ee0376c

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

library/core/src/slice/sort.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,12 @@ where
198198
}
199199

200200
// Choose the greater child.
201-
child += (child + 1 < v.len() && is_less(&v[child], &v[child + 1])) as usize;
201+
if child + 1 < v.len() {
202+
// We need a branch to be sure not to out-of-bounds index,
203+
// but it's highly predictable. The comparison, however,
204+
// is better done branchless, especially for primitives.
205+
child += is_less(&v[child], &v[child + 1]) as usize;
206+
}
202207

203208
// Stop if the invariant holds at `node`.
204209
if !is_less(&v[node], &v[child]) {

0 commit comments

Comments
 (0)