query icon indicating copy to clipboard operation
query copied to clipboard

perf(query-core): useQueries have quadratic performance in relation to the number of queries(#8604)

Open zktm9903 opened this issue 11 months ago • 1 comments

Task

issue comment

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()
    }
  }

zktm9903 avatar Feb 22 '25 10:02 zktm9903

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 a Map<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.

zktm9903 avatar Apr 20 '25 13:04 zktm9903

as discussed in https://github.com/TanStack/query/pull/9467, there is not much to gain from this.

TkDodo avatar Aug 04 '25 17:08 TkDodo