diff --git a/src/directed/astar.rs b/src/directed/astar.rs index 01adcfdb..e8ca3c25 100644 --- a/src/directed/astar.rs +++ b/src/directed/astar.rs @@ -92,7 +92,8 @@ where FH: FnMut(&N) -> C, FS: FnMut(&N) -> bool, { - let mut to_see = BinaryHeap::new(); + // Pre-allocate heap with a reasonable default capacity to reduce reallocations + let mut to_see = BinaryHeap::with_capacity(64); to_see.push(SmallestCostHolder { estimated_cost: Zero::zero(), cost: Zero::zero(), @@ -184,7 +185,8 @@ where FH: FnMut(&N) -> C, FS: FnMut(&N) -> bool, { - let mut to_see = BinaryHeap::new(); + // Pre-allocate heap with a reasonable default capacity to reduce reallocations + let mut to_see = BinaryHeap::with_capacity(64); let mut min_cost = None; let mut sinks = HashSet::new(); to_see.push(SmallestCostHolder { diff --git a/src/undirected/connected_components.rs b/src/undirected/connected_components.rs index 7b6d57e9..1f543d37 100644 --- a/src/undirected/connected_components.rs +++ b/src/undirected/connected_components.rs @@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet}; use std::hash::Hash; use std::marker::PhantomData; -use rustc_hash::{FxHashMap, FxHashSet}; +use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet}; /// A connected component implementation for various generic types. /// @@ -60,7 +60,9 @@ where #[must_use] pub fn separate_components(groups: &[It]) -> (HashMap<&N, usize>, Vec) { let mut table = (0..groups.len()).collect::>(); - let mut indices = HashMap::new(); + // Pre-size the hash map to reduce reallocations + let estimated_capacity = groups.iter().map(|g| g.into_iter().count()).sum(); + let mut indices = HashMap::with_capacity(estimated_capacity); for (mut group_index, group) in groups.iter().enumerate() { let mut is_empty = true; for element in group { @@ -103,7 +105,10 @@ where #[must_use] pub fn components(groups: &[It]) -> C2 { let (_, gindices) = Self::separate_components(groups); - let mut gb: FxHashMap> = FxHashMap::default(); + // Pre-size the hash map to reduce reallocations + let estimated_capacity = gindices.iter().filter(|&&n| n != usize::MAX).count(); + let mut gb: FxHashMap> = + FxHashMap::with_capacity_and_hasher(estimated_capacity, FxBuildHasher); for (i, n) in gindices .into_iter() .enumerate()