@@ -8,7 +8,6 @@ use crate::object::{GC_PERMANENT, GC_UNTRACKED, GcLink};
88use crate :: { AsObject , PyObject , PyObjectRef } ;
99use core:: ptr:: NonNull ;
1010use core:: sync:: atomic:: { AtomicBool , AtomicU32 , AtomicUsize , Ordering } ;
11- use std:: collections:: HashSet ;
1211
1312fn elapsed_secs (
1413 #[ cfg( target_arch = "wasm32" ) ] _start : ( ) ,
@@ -136,6 +135,45 @@ impl GcGeneration {
136135#[ derive( Clone , Copy , PartialEq , Eq , Hash ) ]
137136struct GcPtr ( NonNull < PyObject > ) ;
138137
138+ /// Hashing for the tables a collection keys by an object's address.
139+ ///
140+ /// The default hasher is SipHash, which buys resistance against a caller
141+ /// choosing keys that collide. Nothing chooses these keys: they are addresses
142+ /// this process handed out, and the tables live and die inside one collection.
143+ /// What a collection needs from them is speed -- it hashes every tracked
144+ /// object and every edge between them -- so this runs the address through a
145+ /// handful of multiplies and shifts instead. The shifts are what earns the
146+ /// speed: a table picks its bucket from the low bits, and an address arrives
147+ /// with its low bits zeroed by alignment, so entropy has to be carried
148+ /// downward or every object lands in the same few buckets.
149+ #[ derive( Default ) ]
150+ struct GcPtrHasher ( u64 ) ;
151+
152+ impl core:: hash:: Hasher for GcPtrHasher {
153+ fn finish ( & self ) -> u64 {
154+ self . 0
155+ }
156+
157+ fn write_usize ( & mut self , value : usize ) {
158+ let mut z = ( value as u64 ) . wrapping_add ( 0x9E37_79B9_7F4A_7C15 ) ;
159+ z = ( z ^ ( z >> 30 ) ) . wrapping_mul ( 0xBF58_476D_1CE4_E5B9 ) ;
160+ z = ( z ^ ( z >> 27 ) ) . wrapping_mul ( 0x94D0_49BB_1331_11EB ) ;
161+ self . 0 = z ^ ( z >> 31 ) ;
162+ }
163+
164+ fn write ( & mut self , bytes : & [ u8 ] ) {
165+ // Addresses reach this hasher through `write_usize`; a key hashed any
166+ // other way still has to land somewhere sensible.
167+ for & byte in bytes {
168+ self . 0 = ( self . 0 ^ u64:: from ( byte) ) . wrapping_mul ( 0x0100_0000_01B3 ) ;
169+ }
170+ }
171+ }
172+
173+ type GcBuildHasher = core:: hash:: BuildHasherDefault < GcPtrHasher > ;
174+ type GcSet < T > = std:: collections:: HashSet < T , GcBuildHasher > ;
175+ type GcMap < K , V > = std:: collections:: HashMap < K , V , GcBuildHasher > ;
176+
139177/// RAII barrier that parks every other thread for the pointer-reading phases
140178/// of a collection and lets them run again before finalizers execute.
141179///
@@ -511,7 +549,7 @@ impl GcState {
511549 . map ( |i| self . generation_lists [ i] . read ( ) )
512550 . collect ( ) ;
513551
514- let mut collecting: HashSet < GcPtr > = HashSet :: new ( ) ;
552+ let mut collecting: GcSet < GcPtr > = GcSet :: default ( ) ;
515553 for gen_list in & gen_locks {
516554 for obj in gen_list. iter ( ) {
517555 if obj. strong_count ( ) > 0 {
@@ -550,7 +588,7 @@ impl GcState {
550588 }
551589
552590 // Step 2: Build gc_refs map (copy reference counts)
553- let mut gc_refs: std :: collections :: HashMap < GcPtr , usize > = std :: collections :: HashMap :: new ( ) ;
591+ let mut gc_refs: GcMap < GcPtr , usize > = GcMap :: default ( ) ;
554592
555593 #[ expect(
556594 clippy:: iter_over_hash_type,
@@ -567,8 +605,7 @@ impl GcState {
567605 // of each object's children. Without this, a dict whose write lock is
568606 // held during one traversal but not the other can yield inconsistent
569607 // results, causing live objects to be incorrectly collected.
570- let mut referents_map: std:: collections:: HashMap < GcPtr , Vec < NonNull < PyObject > > > =
571- std:: collections:: HashMap :: new ( ) ;
608+ let mut referents_map: GcMap < GcPtr , Vec < NonNull < PyObject > > > = GcMap :: default ( ) ;
572609
573610 #[ expect(
574611 clippy:: iter_over_hash_type,
@@ -580,19 +617,19 @@ impl GcState {
580617 continue ;
581618 }
582619 let referent_ptrs = unsafe { obj. gc_get_referent_ptrs ( ) } ;
583- referents_map. insert ( ptr, referent_ptrs. clone ( ) ) ;
584- for child_ptr in referent_ptrs {
620+ for & child_ptr in & referent_ptrs {
585621 let gc_ptr = GcPtr ( child_ptr) ;
586622 if collecting. contains ( & gc_ptr)
587623 && let Some ( refs) = gc_refs. get_mut ( & gc_ptr)
588624 {
589625 * refs = refs. saturating_sub ( 1 ) ;
590626 }
591627 }
628+ referents_map. insert ( ptr, referent_ptrs) ;
592629 }
593630
594631 // Step 4: Find reachable objects (gc_refs > 0) and traverse from them
595- let mut reachable: HashSet < GcPtr > = HashSet :: new ( ) ;
632+ let mut reachable: GcSet < GcPtr > = GcSet :: default ( ) ;
596633 let mut worklist: Vec < GcPtr > = Vec :: new ( ) ;
597634
598635 #[ expect(
@@ -609,14 +646,19 @@ impl GcState {
609646 while let Some ( ptr) = worklist. pop ( ) {
610647 let obj = unsafe { ptr. 0 . as_ref ( ) } ;
611648 if obj. is_gc_tracked ( ) {
612- // Reuse the pre-computed referent pointers from step 3.
613- // For objects that were skipped in step 3 (strong_count was 0),
614- // compute them now as a fallback.
615- let referent_ptrs = referents_map
616- . get ( & ptr)
617- . cloned ( )
618- . unwrap_or_else ( || unsafe { obj. gc_get_referent_ptrs ( ) } ) ;
619- for child_ptr in referent_ptrs {
649+ // Reuse the pre-computed referent pointers from step 3, in
650+ // place: copying them out again costs a second pass over every
651+ // edge in the heap. Objects skipped in step 3 (strong_count was
652+ // 0) have none stored and are traversed here instead.
653+ let computed;
654+ let referent_ptrs: & [ NonNull < PyObject > ] = match referents_map. get ( & ptr) {
655+ Some ( stored) => stored,
656+ None => {
657+ computed = unsafe { obj. gc_get_referent_ptrs ( ) } ;
658+ & computed
659+ }
660+ } ;
661+ for & child_ptr in referent_ptrs {
620662 let gc_ptr = GcPtr ( child_ptr) ;
621663 if collecting. contains ( & gc_ptr) && reachable. insert ( gc_ptr) {
622664 worklist. push ( gc_ptr) ;
@@ -639,7 +681,7 @@ impl GcState {
639681 // set_current_frame_nosave), not top_frame.
640682 #[ cfg( all( unix, feature = "threading" , debug_assertions) ) ]
641683 if stw. stopped {
642- let unreachable_set: HashSet < GcPtr > = unreachable. iter ( ) . copied ( ) . collect ( ) ;
684+ let unreachable_set: GcSet < GcPtr > = unreachable. iter ( ) . copied ( ) . collect ( ) ;
643685 let mut cur = crate :: vm:: thread:: get_current_frame ( ) ;
644686 while !cur. is_null ( ) {
645687 let iframe = unsafe { & * cur } ;
@@ -739,7 +781,7 @@ impl GcState {
739781 }
740782
741783 // 6b: Record initial strong counts (for resurrection detection)
742- let initial_counts: std :: collections :: HashMap < GcPtr , usize > = unreachable_refs
784+ let initial_counts: GcMap < GcPtr , usize > = unreachable_refs
743785 . iter ( )
744786 . map ( |obj| {
745787 let ptr = GcPtr ( core:: ptr:: NonNull :: from ( obj. as_ref ( ) ) ) ;
@@ -770,8 +812,8 @@ impl GcState {
770812 }
771813
772814 // Detect resurrection
773- let mut resurrected_set: HashSet < GcPtr > = HashSet :: new ( ) ;
774- let unreachable_set: HashSet < GcPtr > = unreachable. iter ( ) . copied ( ) . collect ( ) ;
815+ let mut resurrected_set: GcSet < GcPtr > = GcSet :: default ( ) ;
816+ let unreachable_set: GcSet < GcPtr > = unreachable. iter ( ) . copied ( ) . collect ( ) ;
775817
776818 for obj in & unreachable_refs {
777819 let ptr = GcPtr ( core:: ptr:: NonNull :: from ( obj. as_ref ( ) ) ) ;
@@ -811,7 +853,7 @@ impl GcState {
811853
812854 // Compute collected count (exclude instance dicts in truly_dead)
813855 let collected = {
814- let dead_ptrs: HashSet < usize > = truly_dead
856+ let dead_ptrs: GcSet < usize > = truly_dead
815857 . iter ( )
816858 . map ( |obj| obj. as_ref ( ) as * const PyObject as usize )
817859 . collect ( ) ;
@@ -869,10 +911,9 @@ impl GcState {
869911 // never be observable through the generation lists, or another
870912 // thread could obtain a strong reference via gc.get_objects()
871913 // and access the cleared payload.
872- let mut late_resurrected: HashSet < GcPtr > = HashSet :: new ( ) ;
914+ let mut late_resurrected: GcSet < GcPtr > = GcSet :: default ( ) ;
873915 if !save_all {
874- let mut expected_counts: std:: collections:: HashMap < GcPtr , usize > =
875- std:: collections:: HashMap :: new ( ) ;
916+ let mut expected_counts: GcMap < GcPtr , usize > = GcMap :: default ( ) ;
876917 for obj_ref in & truly_dead {
877918 let obj = obj_ref. as_ref ( ) ;
878919 if obj. is_gc_tracked ( ) {
@@ -886,8 +927,7 @@ impl GcState {
886927 // the dead set; any surplus in strong_count means another thread
887928 // grabbed a reference before untracking (late resurrection) and
888929 // the object must not be cleared.
889- let mut referents: std:: collections:: HashMap < GcPtr , Vec < NonNull < PyObject > > > =
890- std:: collections:: HashMap :: new ( ) ;
930+ let mut referents: GcMap < GcPtr , Vec < NonNull < PyObject > > > = GcMap :: default ( ) ;
891931 for obj_ref in & truly_dead {
892932 let referent_ptrs = unsafe { obj_ref. gc_get_referent_ptrs ( ) } ;
893933 for child_ptr in & referent_ptrs {
0 commit comments