Skip to content

Commit

Permalink
perf(useQueries): optimize findMatchingObservers fn in queriesObserve…
Browse files Browse the repository at this point in the history
…r for large datasets (#5247)

* perf(useQueries): optimize findMatchingObservers fn in queriesObserver for large datasets

* optimize finding unmatchedObservers in queriesObserver

---------

Co-authored-by: aemad01 <ahmedeamd199824@gmail.com>
  • Loading branch information
AEmad01 and aemad01 committed Apr 10, 2023
1 parent 8969dc1 commit a317633
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions packages/query-core/src/queriesObserver.ts
Expand Up @@ -131,33 +131,35 @@ export class QueriesObserver extends Subscribable<QueriesObserverListener> {
queries: QueryObserverOptions[],
): QueryObserverMatch[] {
const prevObservers = this.observers
const prevObserversMap = new Map(
prevObservers.map((observer) => [observer.options.queryHash, observer]),
)

const defaultedQueryOptions = queries.map((options) =>
this.client.defaultQueryOptions(options),
)

const matchingObservers: QueryObserverMatch[] =
defaultedQueryOptions.flatMap((defaultedOptions) => {
const match = prevObservers.find(
(observer) =>
observer.options.queryHash === defaultedOptions.queryHash,
)
const match = prevObserversMap.get(defaultedOptions.queryHash)
if (match != null) {
return [{ defaultedQueryOptions: defaultedOptions, observer: match }]
}
return []
})

const matchedQueryHashes = matchingObservers.map(
(match) => match.defaultedQueryOptions.queryHash,
const matchedQueryHashes = new Set(
matchingObservers.map((match) => match.defaultedQueryOptions.queryHash),
)
const unmatchedQueries = defaultedQueryOptions.filter(
(defaultedOptions) =>
!matchedQueryHashes.includes(defaultedOptions.queryHash),
(defaultedOptions) => !matchedQueryHashes.has(defaultedOptions.queryHash),
)

const matchingObserversSet = new Set(
matchingObservers.map((match) => match.observer),
)
const unmatchedObservers = prevObservers.filter(
(prevObserver) =>
!matchingObservers.some((match) => match.observer === prevObserver),
(prevObserver) => !matchingObserversSet.has(prevObserver),
)

const getObserver = (options: QueryObserverOptions): QueryObserver => {
Expand Down

0 comments on commit a317633

Please sign in to comment.