Skip to content

Commit 095bf01

Browse files
committed
Improve sift_down performance in BinaryHeap
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.
1 parent 3e826bb commit 095bf01

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

library/alloc/src/collections/binary_heap.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -565,7 +565,7 @@ impl<T: Ord> BinaryHeap<T> {
565565
let mut child = 2 * hole.pos() + 1;
566566

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

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

0 commit comments

Comments
 (0)