Skip to content

Commit

Permalink
Auto merge of #531 - ToMe25:optimize_is_disjoint, r=Amanieu
Browse files Browse the repository at this point in the history
Optimize Set is_disjoint

By using the `Intersection` iterator in `HashSet::is_Disjoint` its performance can be significantly improved in some cases.
This is because `intersection()` always uses the shorter set as its iterator.

It would also be possible to replicate this "Iterate over the smaller set and check in the larger set" logic in the is_disjoint method.
However in my benchmarks the approach I chose is faster than that.

This change only causes a significant improvement when called on the larger of two disjoint sets.

My benchmark results:

Name | Before | After | Diff (%)
-- | -- | -- | --
disjoint_is_disjoint_large_small | 1,147.43 | 535.25 | -53,35 %
disjoint_is_disjoint_small_large | 535.66 | 527.59 | -1,51 %
subset_is_disjoint | 9.90 | 10.44 | 5,45 %
superset_is_disjoint | 9.80 | 10.43 | 6,43 %
  • Loading branch information
bors committed Jun 10, 2024
2 parents 2310a95 + fc448cf commit 62dd521
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1044,7 +1044,7 @@ where
/// assert_eq!(a.is_disjoint(&b), false);
/// ```
pub fn is_disjoint(&self, other: &Self) -> bool {
self.iter().all(|v| !other.contains(v))
self.intersection(other).next().is_none()
}

/// Returns `true` if the set is a subset of another,
Expand Down

0 comments on commit 62dd521

Please sign in to comment.