BTreeSet::from_iter: use bulk building to improve the performance

Apply the same optimization as BTreeMap::from_iter.
This commit is contained in:
Cheng XU 2021-08-28 16:57:58 -07:00
parent cf814d60f8
commit a03287bbf7
No known key found for this signature in database
GPG Key ID: 8794B5D7A3C67F70

View File

@ -1,6 +1,7 @@
// This is pretty much entirely stolen from TreeSet, since BTreeMap has an identical interface
// to TreeMap
use crate::vec::Vec;
use core::borrow::Borrow;
use core::cmp::Ordering::{Equal, Greater, Less};
use core::cmp::{max, min};
@ -1059,9 +1060,17 @@ pub const fn is_empty(&self) -> bool {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> FromIterator<T> for BTreeSet<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
let mut set = BTreeSet::new();
set.extend(iter);
set
let mut inputs: Vec<_> = iter.into_iter().collect();
if inputs.is_empty() {
return BTreeSet::new();
}
// use stable sort to preserve the insertion order.
inputs.sort();
let iter = inputs.into_iter().map(|k| (k, ()));
let map = BTreeMap::bulk_build_from_sorted_iter(iter);
BTreeSet { map }
}
}
@ -1074,8 +1083,16 @@ fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
/// let set2: BTreeSet<_> = [1, 2, 3, 4].into();
/// assert_eq!(set1, set2);
/// ```
fn from(arr: [T; N]) -> Self {
core::array::IntoIter::new(arr).collect()
fn from(mut arr: [T; N]) -> Self {
if N == 0 {
return BTreeSet::new();
}
// use stable sort to preserve the insertion order.
arr.sort();
let iter = core::array::IntoIter::new(arr).map(|k| (k, ()));
let map = BTreeMap::bulk_build_from_sorted_iter(iter);
BTreeSet { map }
}
}