Skip to content

Commit b7089e0

Browse files
committed
Auto merge of #107894 - Voultapher:improve-heapsort-fallback, r=scottmcm
Speedup heapsort by 1.5x by making it branchless `slice::sort_unstable` will fall back to heapsort if it repeatedly fails to find a good pivot. By making the core child update code branchless it is much faster. On Zen3 sorting 10k `u64` and forcing the sort to pick heapsort, results in: 455us -> 278us
2 parents d094016 + ee0376c commit b7089e0

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

library/core/src/slice/sort.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -198,8 +198,11 @@ where
198198
}
199199

200200
// Choose the greater child.
201-
if child + 1 < v.len() && is_less(&v[child], &v[child + 1]) {
202-
child += 1;
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;
203206
}
204207

205208
// Stop if the invariant holds at `node`.

0 commit comments

Comments
 (0)