perf(query-core): Improve performance of mutationCache #8450
+41
−25
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hey friends. I was looking at the implementation of mutationCache while investigating an issue in Next.js related to our new
dynamicIO
experimental flag. With this flag on, during prerendering, sync IO like reading the system clock will bail out of prerendering unless you explicitly cache it. Turns out the mutationCache usesDate.now()
to seed an ID to avoid collisions of scopes when hydrating mutations which is what initiated the original issue in Next.jsthe mutationCache implementation isn't wrong but since it can be made more efficient by not using a derived scope I put together this PR to implement a perf improvement that also happens to avoid deopting out of prerendering in this case.
Implementation Notes
The mutationCache implementation models all mutations as scoped even when the scope is implicit. With implicit scopes there can only ever be one mutation per scope so the overhead of tracking the scope is unnecessary. Additionally because scopes need a unique value the current implementation bootstraps this value using a random source (Date.now()). While this is practically likely to be fine it is not impossible that there is a scope collision with mutation hydration. Modeling the internal state of the cache without deriving virtual scopes simplifies the implementation in memory and code and avoids the possibility of scope collision by design. This should provide a modest perf bump for mutations that do not use scopes and be neutral for mutations that do use scopes.