Skip to content

Commit 7e07219

Browse files
committed
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
1 parent d1ac43a commit 7e07219

File tree

1 file changed

+1
-3
lines changed

1 file changed

+1
-3
lines changed

library/core/src/slice/sort.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -198,9 +198,7 @@ where
198198
}
199199

200200
// Choose the greater child.
201-
if child + 1 < v.len() && is_less(&v[child], &v[child + 1]) {
202-
child += 1;
203-
}
201+
child += (child + 1 < v.len() && is_less(&v[child], &v[child + 1])) as usize;
204202

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

0 commit comments

Comments
 (0)