Repository navigation
Closed
Labels
A-btreeArea: `std::collections::{BTreeMap, BTreeSet}`Area: `std::collections::{BTreeMap, BTreeSet}`C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCCategory: An issue tracking the progress of sth. like the implementation of an RFCI-slowIssue: Problems and improvements with respect to performance of generated code.Issue: Problems and improvements with respect to performance of generated code.T-libs-api[DEPRECATED; DO NOT USE][DEPRECATED; DO NOT USE]disposition-mergeThis issue / PR is in PFCP or FCP with a disposition to merge it.This issue / PR is in PFCP or FCP with a disposition to merge it.finished-final-comment-periodThe final comment period is finished for this PR / Issue.The final comment period is finished for this PR / Issue.
Description
Feature gate: #![feature(map_first_last)]
Public API
impl<T> BTreeSet<T> {
pub fn first(&self) -> Option<&T> where T: Ord;
pub fn last(&self) -> Option<&T> where T: Ord;
pub fn pop_first(&mut self) -> Option<T> where T: Ord;
pub fn pop_last(&mut self) -> Option<T> where T: Ord;
}
impl<K, V> BTreeMap<K, V> {
pub fn first_key_value(&self) -> Option<(&K, &V)> where K: Ord;
pub fn last_key_value(&self) -> Option<(&K, &V)> where K: Ord;
pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> where K: Ord;
pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> where K: Ord;
pub fn pop_first(&mut self) -> Option<(K, V)> where K: Ord;
pub fn pop_last(&mut self) -> Option<(K, V)> where K: Ord;
}Steps / History
- Implementation: proposal for BTreeMap/Set min/max, #62924 #65637
- Changes: BTreeMap first last proposal tweaks #70850
- Final commenting period (FCP)
- Stabilization PR
Unresolved Questions
- Naming (min/max, first/last, front/back, .. ?)
- For BTreeMap: Separate entry and pair (and just-value) functions?
Original issue title: Finding minimum/maximum element in BTreeMap does twice the required amount of computation
Original issue text:
The standard way of finding the minimum element in BTreeMap is tree_map.iter().next()
The iter() function creates a btree_map::Iter, which finds both the minimum and maximum element to create its internal instance of btree_map::Range.
This is unnecessary, and a BTreeMap::get_min or similar function could be provided, which would just internally call the first_leaf_edge private function, without needing to call last_leaf_edge.
Ditto for finding the maximum element.
Reacted by Benjamin Saunders, mseravalli, Stanislav Tkach, João Marcos, Aidan Beggs, behzad nouri, Sebastian Urban, Connor Skees, Alex, im-nefilim and 62 more
Reacted by leonardo-m, Adithya Dsilva, cottonguard, Adrian Ratiu, Ryo Onodera, Felipe S. S. Schneider, Rageking8, cyqsimon, Aleksandr Kovalev, leo-ship-it and 1 more
Reacted by Xie Ruifeng, Ruifeng Xie, Rob, pYtoner, Tim Fish, Lily, Iohann Rabeson, Adithya Dsilva, Adrián Delgado, Ryo Onodera and 4 more
Metadata
Metadata
Assignees
Labels
A-btreeArea: `std::collections::{BTreeMap, BTreeSet}`Area: `std::collections::{BTreeMap, BTreeSet}`C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCCategory: An issue tracking the progress of sth. like the implementation of an RFCI-slowIssue: Problems and improvements with respect to performance of generated code.Issue: Problems and improvements with respect to performance of generated code.T-libs-api[DEPRECATED; DO NOT USE][DEPRECATED; DO NOT USE]disposition-mergeThis issue / PR is in PFCP or FCP with a disposition to merge it.This issue / PR is in PFCP or FCP with a disposition to merge it.finished-final-comment-periodThe final comment period is finished for this PR / Issue.The final comment period is finished for this PR / Issue.
Activity
[-]Finding inimum/maximum element in BTreeMap does twice the required computation[/-][+]Finding minimum/maximum element in BTreeMap does twice the required amount of computation[/+]cuviper commentedon Jul 24, 2019
Here are what the other collections call similar methods:
[T]slices (andVecvia deref) havefirst/first_mutandlast/last_mut.VecDequeandLinkedListhavefront/front_mutandback/back_mut.BinaryHeaphaspeekandpeek_mut, i.e. only from the front.HashMapandHashSetare unordered, and have no such methods.strandStringhave no such methods.cuviper commentedon Jul 24, 2019
#59947 is related --
Iterator::min/maxare even worse since they naively walk everything.ssomers commentedon Oct 19, 2019
#64820 is also related - BTreeSet is_subset, intersection and difference now always do this double work (they actually want both min and max at the same time, but requesting both
nextandnext_backfrom the same iterator that may only see one element is not the most straightforward code).I naively thought the redundant data (the other end and iterator length) and code would all get optimized away from an expression like
tree_map.iter().next(), but after writing out code to avoid the double work in BTreeSet::is_subset, benchmarks report a 20 to 40% speed boost, for the cases where it can quickly bail out after getting min and max either side and comparing them. I'm going to measure the effect by adding the desired functions to map, and if successful I can put them in a pull request, but I have no idea what the procedure is for adding APIs. I vote forfirstandlastas names.ssomers commentedon Oct 20, 2019
According to a raw benchmark, the specialized functions are about 3 times faster than
.iter().next(). By the way,.range(..).next()is a little slower for small sets, despite not bothering with iterator length, presumably becauseiter()has access to internals to construct its unbounded range.Details: benchmark code in liballoc/benches/btree/map.rs:
Results using the new functions:
Results using .iter().next() / .iter().next_back():
Results using .range(..).next() / .range(..).next_back():
Auto merge of #65637 - ssomers:master, r=scottmcm
matklad commentedon Dec 26, 2019
I vote for min/max rather than first/last terminology. Rationale: I’ve recently had a bad bug when I used Rust’s BinaryHeap and assumed that pop yields a minimal item. If the API had used max in the method name, I wouldn’t have made the bug.
This case is similar: first is ambiguous, min is precise (and shorter ^^).
ssomers commentedon Dec 26, 2019
I'm slightly in favour of min/max at the moment, having faced reverse iteration in (other) code with first/last names. It's a close call; min/max is ambiguous about performance, because many min/max functions out there are in fact linear searches. PS then again, that argument makes
lastdouble ambiguous, becauselaston an iterator can be sluggish (meticulously consume an iterator) or instant (on a well-behaved implementation ofDoubleEndedIterator).matklad commentedon Dec 26, 2019
Correctness is more important than performance, and the performance ambiguity is an a safe direction (operation is faster than it might seem)
jmlMetaswitch commentedon Mar 16, 2020
Can we also get
popforms that remove the entry at the same time? (I think that's probably better thantakeor other synonyms, especially asBTreeSethaspop_last.) They are particularly useful in algorithms that repeatedly process the max/min and may add entries during that processing (e.g A*). I think that suggests (from the above)max_key_value,max_entry,pop_max_key_valueand the equivalent formin.ssomers commentedon Mar 16, 2020
I didn't add those back then because I thought they were intended to be used through the entry API. But using that in practice seems more complicated than I would want. There's no entry concept in BTreeSet, so
pop_Xseemed the only option there.I wouldn't start mixing the naming scheme though. First/last or min/max (or something else) all the way.
I don't remember any discussion on whether it should be
poportake(orpoll, anyone?) but there are lots of similarpops in Rust's standard library, the existingtakes on sets work with a particular key, and the othertakes seem to grab the entire contents.91 remaining items
Rollup merge of rust-lang#101727 - est31:stabilize_map_first_last, r=…
Rollup merge of rust-lang#101727 - est31:stabilize_map_first_last, r=…
Rollup merge of #101727 - est31:stabilize_map_first_last, r=m-ou-se
Rollup merge of #101727 - est31:stabilize_map_first_last, r=m-ou-se
Rollup merge of #101727 - est31:stabilize_map_first_last, r=m-ou-se
Rollup merge of #101727 - est31:stabilize_map_first_last, r=m-ou-se
Rollup merge of #101727 - est31:stabilize_map_first_last, r=m-ou-se
Rollup merge of #101727 - est31:stabilize_map_first_last, r=m-ou-se
refactor(kad): replace BTreeMap::remove(Iter::next_back) with pop_last
refactor(kad): replace BTreeMap::remove(Iter::next_back) with pop_last
refactor(kad): replace BTreeMap::remove(Iter::next_back) with pop_last