Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a WeakMap cache for query arg serialization for perf #3193

Merged
merged 1 commit into from
Feb 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 27 additions & 10 deletions packages/toolkit/src/query/defaultSerializeQueryArgs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,38 @@ import type { QueryCacheKey } from './core/apiState'
import type { EndpointDefinition } from './endpointDefinitions'
import { isPlainObject } from '@reduxjs/toolkit'

const cache: WeakMap<any, string> | undefined = WeakMap
? new WeakMap()
: undefined

export const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({
endpointName,
queryArgs,
}) => {
let serialized = ''

const cached = cache?.get(queryArgs)

if (typeof cached === 'string') {
serialized = cached
} else {
const stringified = JSON.stringify(queryArgs, (key, value) =>
isPlainObject(value)
? Object.keys(value)
.sort()
.reduce<any>((acc, key) => {
acc[key] = (value as any)[key]
return acc
}, {})
: value
)
if (isPlainObject(queryArgs)) {
cache?.set(queryArgs, stringified)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. There is a slight worry that two objects with the same shape will get two different entries in the map since the map is based off memory address and not value, but this shouldn't blow up in memory since I would assume old entries can get garbage collected

}
serialized = stringified
}
// Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })
return `${endpointName}(${JSON.stringify(queryArgs, (key, value) =>
isPlainObject(value)
? Object.keys(value)
.sort()
.reduce<any>((acc, key) => {
acc[key] = (value as any)[key]
return acc
}, {})
: value
)})`
return `${endpointName}(${serialized})`
}

export type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
Expand Down
66 changes: 66 additions & 0 deletions packages/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,69 @@ test('nested object arg is sorted recursively', () => {
`"test({\\"age\\":5,\\"name\\":{\\"first\\":\\"Banana\\",\\"last\\":\\"Split\\"}})"`
)
})

test('Fully serializes a deeply nested object', () => {
const nestedObj = {
a: {
a1: {
a11: {
a111: 1,
},
},
},
b: {
b2: {
b21: 3,
},
b1: {
b11: 2,
},
},
}

const res = defaultSerializeQueryArgs({
endpointDefinition,
endpointName,
queryArgs: nestedObj,
})
expect(res).toMatchInlineSnapshot(
`"test({\\"a\\":{\\"a1\\":{\\"a11\\":{\\"a111\\":1}}},\\"b\\":{\\"b1\\":{\\"b11\\":2},\\"b2\\":{\\"b21\\":3}}})"`
)
})

test('Caches results for plain objects', () => {
const testData = Array.from({ length: 10000 }).map((_, i) => {
return {
albumId: i,
id: i,
title: 'accusamus beatae ad facilis cum similique qui sunt',
url: 'https://via.placeholder.com/600/92c952',
thumbnailUrl: 'https://via.placeholder.com/150/92c952',
}
})

const data = {
testData,
}

const runWithTimer = (data: any) => {
const start = Date.now()
const res = defaultSerializeQueryArgs({
endpointDefinition,
endpointName,
queryArgs: data,
})
const end = Date.now()
const duration = end - start
return [res, duration] as const
}

const [res1, time1] = runWithTimer(data)
const [res2, time2] = runWithTimer(data)

expect(res1).toBe(res2)
expect(time2).toBeLessThanOrEqual(time1)
// Locally, stringifying 10K items takes 25-30ms.
// Assuming the WeakMap cache hit, this _should_ be 0
expect(time2).toBeLessThan(2)
})