Skip to content

Remove unpredicted branch from kmerge::sift_down #518

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

Merged
merged 1 commit into from
Jan 20, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions src/kmerge_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,13 @@ fn sift_down<T, S>(heap: &mut [T], index: usize, mut less_than: S)
debug_assert!(index <= heap.len());
let mut pos = index;
let mut child = 2 * pos + 1;
// the `pos` conditional is to avoid a bounds check
while pos < heap.len() && child < heap.len() {
let right = child + 1;

// Require the right child to be present
// This allows to find the index of the smallest child without a branch
// that wouldn't be predicted if present
while child + 1 < heap.len() {
// pick the smaller of the two children
if right < heap.len() && less_than(&heap[right], &heap[child]) {
child = right;
}
// use aritmethic to avoid an unpredictable branch
child += less_than(&heap[child+1], &heap[child]) as usize;

// sift down is done if we are already in order
if !less_than(&heap[child], &heap[pos]) {
Expand All @@ -91,6 +90,11 @@ fn sift_down<T, S>(heap: &mut [T], index: usize, mut less_than: S)
pos = child;
child = 2 * pos + 1;
}
// Check if the last (left) child was an only child
// if it is then it has to be compared with the parent
if child + 1 == heap.len() && less_than(&heap[child], &heap[pos]) {
heap.swap(pos, child);
}
}

/// An iterator adaptor that merges an abitrary number of base iterators in ascending order.
Expand Down