Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speedup heapsort by 1.8x by making it branchless #107894

Merged
merged 2 commits into from
Feb 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 5 additions & 2 deletions library/core/src/slice/sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,11 @@ where
}

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

// Stop if the invariant holds at `node`.
Expand Down