perf(query-core): useQueries have quadratic performance in relation to the number of queries(#8604)
Task
Modification
This change optimizes the time complexity of the #onUpdate function in queriesObserver from O(n) to O(1).
#onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
const index = this.#observerMap.get(observer)
if (index !== undefined) {
this.#result = replaceAt(this.#result, index, result)
this.#notify()
}
}
I’m not a fan of storing the observers in both a Map and an Array, and the whole thing becomes more complex.
The only reason we have an Array is because users pass in
Array<QueryObserverOptions>, and we need to keep that order. Maybe storing this as aMap<index, QueryObserver>only would work?
You're absolutely right. Fundamentally, we need to preserve the order, so using an array is necessary. Alternatively, it’s possible to use a Map and include the order in the values (rather than the keys), but based on my attempt, it significantly increased code complexity. I believe this PR improves performance while keeping the code complexity to a minimum, though I completely agree with your concerns regarding complexity as well.
as discussed in https://github.com/TanStack/query/pull/9467, there is not much to gain from this.