Commit 4088981
authored
Rollup merge of #78857 - SkiFire13:bheap-opt, r=KodrAus
Improve BinaryHeap performance
By changing the condition in the loops from `child < end` to `child < end - 1` we're guaranteed that `right = child + 1 < end` and since finding the index of the biggest sibling can be done with an arithmetic operation we can remove a branch from the loop body. The case where there's no right child, i.e. `child == end - 1` is instead handled outside the loop, after it ends; note that if the loops ends early we can use `return` instead of `break` since the check `child == end - 1` will surely fail.
I've also removed a call to `<[T]>::swap` that was hiding a bound check that [wasn't being optimized by LLVM](https://godbolt.org/z/zrhdGM).
A quick benchmarks on my pc shows that the gains are pretty significant:
|name |before ns/iter |after ns/iter |diff ns/iter |diff % |speedup |
|---------------------|----------------|---------------|--------------|----------|--------|
|find_smallest_1000 | 352,565 | 260,098 | -92,467 | -26.23% | x 1.36 |
|from_vec | 676,795 | 473,934 | -202,861 | -29.97% | x 1.43 |
|into_sorted_vec | 469,511 | 304,275 | -165,236 | -35.19% | x 1.54 |
|pop | 483,198 | 373,778 | -109,420 | -22.64% | x 1.29 |
The other 2 benchmarks for `BinaryHeap` (`peek_mut_deref_mut` and `push`) weren't impacted and as such didn't show any significant change.1 file changed
+19
-13
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
495 | 495 | | |
496 | 496 | | |
497 | 497 | | |
498 | | - | |
| 498 | + | |
| 499 | + | |
| 500 | + | |
| 501 | + | |
| 502 | + | |
| 503 | + | |
| 504 | + | |
| 505 | + | |
499 | 506 | | |
500 | 507 | | |
501 | 508 | | |
| |||
531 | 538 | | |
532 | 539 | | |
533 | 540 | | |
534 | | - | |
535 | | - | |
| 541 | + | |
536 | 542 | | |
537 | | - | |
538 | | - | |
539 | | - | |
| 543 | + | |
540 | 544 | | |
541 | 545 | | |
542 | | - | |
| 546 | + | |
543 | 547 | | |
544 | 548 | | |
545 | 549 | | |
546 | 550 | | |
| 551 | + | |
| 552 | + | |
| 553 | + | |
547 | 554 | | |
548 | 555 | | |
549 | 556 | | |
| |||
563 | 570 | | |
564 | 571 | | |
565 | 572 | | |
566 | | - | |
567 | | - | |
568 | | - | |
569 | | - | |
570 | | - | |
571 | | - | |
| 573 | + | |
| 574 | + | |
572 | 575 | | |
573 | 576 | | |
574 | 577 | | |
| 578 | + | |
| 579 | + | |
| 580 | + | |
575 | 581 | | |
576 | 582 | | |
577 | 583 | | |
| |||
0 commit comments