Skip to content

Commit

Permalink
Improve sift_down performance in BinaryHeap
Browse files Browse the repository at this point in the history
Because child > 0, the two statements are equivalent, but using
saturating_sub and <= yields in faster code. This is most notable in the
binary_heap::bench_into_sorted_vec benchmark, which shows a speedup of
1.26x, which uses sift_down_range internally. The speedup of pop (that
uses sift_down_to_bottom internally) is much less significant as the
sifting method is not called in a loop.
  • Loading branch information
hanmertens committed Feb 21, 2021
1 parent 3e826bb commit 095bf01
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions library/alloc/src/collections/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,7 @@ impl<T: Ord> BinaryHeap<T> {
let mut child = 2 * hole.pos() + 1;

// Loop invariant: child == 2 * hole.pos() + 1.
while child < end - 1 {
while child <= end.saturating_sub(2) {
// compare with the greater of the two children
// SAFETY: child < end - 1 < self.len() and
// child + 1 < end <= self.len(), so they're valid indexes.
Expand Down Expand Up @@ -624,7 +624,7 @@ impl<T: Ord> BinaryHeap<T> {
let mut child = 2 * hole.pos() + 1;

// Loop invariant: child == 2 * hole.pos() + 1.
while child < end - 1 {
while child <= end.saturating_sub(2) {
// SAFETY: child < end - 1 < self.len() and
// child + 1 < end <= self.len(), so they're valid indexes.
// child == 2 * hole.pos() + 1 != hole.pos() and
Expand Down

0 comments on commit 095bf01

Please sign in to comment.