Skip to content

Commit 2c60ecb

Browse files
committed
Auto merge of #130 - stepancheg:smaller-larger, r=Amanieu
Optimize set union and intersection For intersection: take the smaller set, and check each element exists in the larger set. For union: take the larger set, and append missing elements from the smaller set. Similar optimizations exist in Rust's `HashSet`.
2 parents 629fa19 + d5cc5a8 commit 2c60ecb

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/set.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -517,9 +517,14 @@ where
517517
/// ```
518518
#[cfg_attr(feature = "inline-more", inline)]
519519
pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T, S> {
520+
let (smaller, larger) = if self.len() <= other.len() {
521+
(self, other)
522+
} else {
523+
(other, self)
524+
};
520525
Intersection {
521-
iter: self.iter(),
522-
other,
526+
iter: smaller.iter(),
527+
other: larger,
523528
}
524529
}
525530

@@ -543,8 +548,13 @@ where
543548
/// ```
544549
#[cfg_attr(feature = "inline-more", inline)]
545550
pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T, S> {
551+
let (smaller, larger) = if self.len() <= other.len() {
552+
(self, other)
553+
} else {
554+
(other, self)
555+
};
546556
Union {
547-
iter: self.iter().chain(other.difference(self)),
557+
iter: larger.iter().chain(smaller.difference(larger)),
548558
}
549559
}
550560

0 commit comments

Comments
 (0)