@@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet};
55use std:: hash:: Hash ;
66use 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///
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