Skip to content

Commit 80556b3

Browse files
committed
perf: pre-allocate hash maps
1 parent d5aceb5 commit 80556b3

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

src/undirected/connected_components.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet};
55
use std::hash::Hash;
66
use std::marker::PhantomData;
77

8-
use rustc_hash::{FxHashMap, FxHashSet};
8+
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
99

1010
/// A connected component implementation for various generic types.
1111
///
@@ -60,7 +60,9 @@ where
6060
#[must_use]
6161
pub fn separate_components(groups: &[It]) -> (HashMap<&N, usize>, Vec<usize>) {
6262
let mut table = (0..groups.len()).collect::<Vec<_>>();
63-
let mut indices = HashMap::new();
63+
// Pre-size the hash map to reduce reallocations
64+
let estimated_capacity = groups.iter().map(|g| g.into_iter().count()).sum();
65+
let mut indices = HashMap::with_capacity(estimated_capacity);
6466
for (mut group_index, group) in groups.iter().enumerate() {
6567
let mut is_empty = true;
6668
for element in group {
@@ -103,7 +105,10 @@ where
103105
#[must_use]
104106
pub fn components(groups: &[It]) -> C2 {
105107
let (_, gindices) = Self::separate_components(groups);
106-
let mut gb: FxHashMap<usize, FxHashSet<N>> = FxHashMap::default();
108+
// Pre-size the hash map to reduce reallocations
109+
let estimated_capacity = gindices.iter().filter(|&&n| n != usize::MAX).count();
110+
let mut gb: FxHashMap<usize, FxHashSet<N>> =
111+
FxHashMap::with_capacity_and_hasher(estimated_capacity, FxBuildHasher);
107112
for (i, n) in gindices
108113
.into_iter()
109114
.enumerate()

0 commit comments

Comments
 (0)