Skip to content

Improve BinaryHeap performance #78857

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 4 commits into from
Nov 13, 2020
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
32 changes: 19 additions & 13 deletions library/alloc/src/collections/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,14 @@ impl<T: Ord> BinaryHeap<T> {
let mut end = self.len();
while end > 1 {
end -= 1;
self.data.swap(0, end);
// SAFETY: `end` goes from `self.len() - 1` to 1 (both included),
// so it's always a valid index to access.
// It is safe to access index 0 (i.e. `ptr`), because
// 1 <= end < self.len(), which means self.len() >= 2.
unsafe {
let ptr = self.data.as_mut_ptr();
ptr::swap(ptr, ptr.add(end));
}
self.sift_down_range(0, end);
}
self.into_vec()
Expand Down Expand Up @@ -531,19 +538,19 @@ impl<T: Ord> BinaryHeap<T> {
unsafe {
let mut hole = Hole::new(&mut self.data, pos);
let mut child = 2 * pos + 1;
while child < end {
let right = child + 1;
while child < end - 1 {
// compare with the greater of the two children
if right < end && hole.get(child) <= hole.get(right) {
child = right;
}
child += (hole.get(child) <= hole.get(child + 1)) as usize;
// if we are already in order, stop.
if hole.element() >= hole.get(child) {
break;
return;
}
hole.move_to(child);
child = 2 * hole.pos() + 1;
}
if child == end - 1 && hole.element() < hole.get(child) {
hole.move_to(child);
}
}
}

Expand All @@ -563,15 +570,14 @@ impl<T: Ord> BinaryHeap<T> {
unsafe {
let mut hole = Hole::new(&mut self.data, pos);
let mut child = 2 * pos + 1;
while child < end {
let right = child + 1;
// compare with the greater of the two children
if right < end && hole.get(child) <= hole.get(right) {
child = right;
}
while child < end - 1 {
child += (hole.get(child) <= hole.get(child + 1)) as usize;
hole.move_to(child);
child = 2 * hole.pos() + 1;
}
if child == end - 1 {
hole.move_to(child);
}
pos = hole.pos;
}
self.sift_up(start, pos);
Expand Down