Skip to content

Commit 19c5ec4

Browse files
authored
Merge pull request #645 from callstack-internal/perf/improve-matching-keys-lookup
perf: improve finding matching keys in subscription
2 parents ba6be93 + df39e04 commit 19c5ec4

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

lib/OnyxUtils.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1295,12 +1295,21 @@ function subscribeToKey<TKey extends OnyxKey>(connectOptions: ConnectOptions<TKe
12951295
// can send data back to the subscriber. Note that multiple keys can match as a subscriber could either be
12961296
// subscribed to a "collection key" or a single key.
12971297
const matchingKeys: string[] = [];
1298-
keys.forEach((key) => {
1299-
if (!isKeyMatch(mapping.key, key)) {
1300-
return;
1298+
1299+
// Performance optimization: For single key subscriptions, avoid O(n) iteration
1300+
if (!isCollectionKey(mapping.key)) {
1301+
if (keys.has(mapping.key)) {
1302+
matchingKeys.push(mapping.key);
13011303
}
1302-
matchingKeys.push(key);
1303-
});
1304+
} else {
1305+
// Collection case - need to iterate through all keys to find matches (O(n))
1306+
keys.forEach((key) => {
1307+
if (!isKeyMatch(mapping.key, key)) {
1308+
return;
1309+
}
1310+
matchingKeys.push(key);
1311+
});
1312+
}
13041313
// If the key being connected to does not exist we initialize the value with null. For subscribers that connected
13051314
// directly via connect() they will simply get a null value sent to them without any information about which key matched
13061315
// since there are none matched. In withOnyx() we wait for all connected keys to return a value before rendering the child

0 commit comments

Comments
 (0)