diff options
| author | bors <bors@rust-lang.org> | 2020-09-21 05:31:01 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2020-09-21 05:31:01 +0000 |
| commit | a409a233e02b1864d1b76495a1f946bb56c7aeb2 (patch) | |
| tree | 0898049b3dd32714fea96f03a843b6b532ad329b /library/alloc/src/collections | |
| parent | 70148d7b3161912381b1a5c427c3a690e12c5b24 (diff) | |
| parent | ca15e9d8a11e7c25eb85930d1da3009647c1680e (diff) | |
| download | rust-a409a233e02b1864d1b76495a1f946bb56c7aeb2.tar.gz rust-a409a233e02b1864d1b76495a1f946bb56c7aeb2.zip | |
Auto merge of #75974 - SkiFire13:peekmut-opt-sift, r=LukasKalbertodt
Avoid useless sift_down when std::collections::binary_heap::PeekMut is never mutably dereferenced If `deref_mut` is never called then it's not possible for the element to be mutated without internal mutability, meaning there's no need to call `sift_down`. This could be a little improvement in cases where you want to mutate the biggest element of the heap only if it satisfies a certain predicate that needs only read access to the element.
Diffstat (limited to 'library/alloc/src/collections')
| -rw-r--r-- | library/alloc/src/collections/binary_heap.rs | 6 |
1 files changed, 4 insertions, 2 deletions
diff --git a/library/alloc/src/collections/binary_heap.rs b/library/alloc/src/collections/binary_heap.rs index 621c4ff6378..ea75fa21965 100644 --- a/library/alloc/src/collections/binary_heap.rs +++ b/library/alloc/src/collections/binary_heap.rs @@ -291,6 +291,7 @@ impl<T: Ord> Deref for PeekMut<'_, T> { impl<T: Ord> DerefMut for PeekMut<'_, T> { fn deref_mut(&mut self) -> &mut T { debug_assert!(!self.heap.is_empty()); + self.sift = true; // SAFE: PeekMut is only instantiated for non-empty heaps unsafe { self.heap.data.get_unchecked_mut(0) } } @@ -396,10 +397,11 @@ impl<T: Ord> BinaryHeap<T> { /// /// # Time complexity /// - /// Cost is *O*(1) in the worst case. + /// If the item is modified then the worst case time complexity is *O*(log(*n*)), + /// otherwise it's *O*(1). #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")] pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> { - if self.is_empty() { None } else { Some(PeekMut { heap: self, sift: true }) } + if self.is_empty() { None } else { Some(PeekMut { heap: self, sift: false }) } } /// Removes the greatest item from the binary heap and returns it, or `None` if it |
