@@ -8,6 +8,7 @@ typedef CacheStateSnapshot<K, V extends Object> = ({
88 Map <K , WeakReference <V >> cache,
99 ListQueue <WeakReference <V >> removeQueue,
1010 Expando <bool > containsExpando,
11+ Expando <(K ,)> referenceKeys,
1112});
1213
1314/// Aggregation of [CacheState] main properties with details
@@ -33,9 +34,11 @@ class CacheState<K, V extends Object> {
3334 final cache = < K , WeakReference <V >> {};
3435 /// Queue for delayed concurrent modifications.
3536 final removeQueue = ListQueue <WeakReference <V >>();
36- /// [Expando] used to optimize `containsValue` calls and bypass using
37+ /// [Expando] used to optimize `containsValue` calls and bypass usage
3738 /// of iteration.
3839 final containsExpando = Expando <bool >();
40+ /// [Expando] used to optimize `remove` calls and bypass usage of iteration.
41+ final referenceKeys = Expando <(K ,)>();
3942
4043 /// [Finalizer] that manages [cache] .
4144 static final cacheFinalizer = Finalizer <CacheStateSnapshotWithReference <Object ?, Object >>(
@@ -54,28 +57,31 @@ class CacheState<K, V extends Object> {
5457 ) = argument;
5558 if (mutex? .isLocked != true )
5659 return removeCacheEntryStatic (argument);
57- removeQueue.addLast (reference);
60+ return removeQueue.addLast (reference);
5861 }
5962
6063 /// Removes cache entry from [cache] table and detach finalizer form it.
6164 static void removeCacheEntryStatic <K , V extends Object >(
6265 CacheStateSnapshotWithReference <K , V > argument,
6366 ) {
6467 final CacheStateSnapshotWithReference (
65- snapshot: CacheStateSnapshot (: cache, : containsExpando),
68+ snapshot: CacheStateSnapshot (: cache, : containsExpando, : referenceKeys ),
6669 : reference,
6770 ) = argument;
6871 cacheFinalizer.detach (reference);
72+ if (referenceKeys[reference] case (final key,) when cache[key] == reference)
73+ cache.remove (key);
74+ referenceKeys[reference] = null ;
6975 if (reference.target case final target? )
7076 containsExpando[target] = null ;
71- cache.removeWhere ((key, value) => value == reference);
7277 }
7378
7479 /// Get aggregation of [CacheState] main properties.
7580 CacheStateSnapshot <K , V > get snapshot => (
7681 cache: cache,
7782 removeQueue: removeQueue,
7883 containsExpando: containsExpando,
84+ referenceKeys: referenceKeys,
7985 );
8086
8187 /// Create aggregation of [CacheState] properties required for value deletion.
@@ -99,6 +105,7 @@ class CacheState<K, V extends Object> {
99105 }
100106 containsExpando[value] = true ;
101107 final reference = cache[key] = WeakReference <V >(value);
108+ referenceKeys[reference] = (key,);
102109 cacheFinalizer.attach (
103110 value,
104111 makeSnapshotWithReference (reference),
@@ -113,6 +120,7 @@ class CacheState<K, V extends Object> {
113120 return null ;
114121 }
115122 cacheFinalizer.detach (reference);
123+ referenceKeys[reference] = null ;
116124 if (reference.target case final target? )
117125 containsExpando[target] = null ;
118126 return reference.target;
0 commit comments