Skip to content

Commit 44a8c3e

Browse files
authored
perf(router-core): skip impossible JSON parse attempts (#8006)
* perf(router-core): skip impossible JSON parses * perf(router-core): refine JSON parse fast path * changeset
1 parent c59788c commit 44a8c3e

4 files changed

Lines changed: 240 additions & 5 deletions

File tree

‎.changeset/dirty-bushes-sink.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/router-core': patch
3+
---
4+
5+
skip impossible JSON parse attempts

‎packages/router-core/src/searchParams.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { decode, encode } from './qss'
22
import type { AnySchema } from './validators'
33

4+
// JSON can start with whitespace, ", [, {, -, a digit, or fa/nu/tr.
5+
// False positives safely fall through to JSON.parse.
6+
const jsonStart = /^(?:\s|["[{\d-]|fa|nu|tr)/
7+
48
/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
59
export const defaultParseSearch = parseSearchWith(JSON.parse)
610
/** Default `stringifySearch` using JSON.stringify for complex values. */
@@ -59,15 +63,19 @@ export function stringifySearchWith(
5963
stringify: (search: any) => string,
6064
parser?: (str: string) => any,
6165
) {
62-
const hasParser = typeof parser === 'function'
66+
const isJsonParser = parser === JSON.parse
6367
function stringifyValue(val: any) {
64-
if (typeof val === 'object' && val !== null) {
68+
if (val && typeof val === 'object') {
6569
try {
6670
return stringify(val)
6771
} catch (_err) {
6872
// silent
6973
}
70-
} else if (hasParser && typeof val === 'string') {
74+
} else if (parser && typeof val === 'string') {
75+
// Skip JSON.parse when the value cannot begin valid JSON.
76+
if (isJsonParser && !jsonStart.test(val)) {
77+
return val
78+
}
7179
try {
7280
// Check if it's a valid parseable string.
7381
// If it is, then stringify it again.
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
import { bench, describe, expect } from 'vitest'
2+
import { defaultStringifySearch } from '../src'
3+
4+
const iterations = 1_000
5+
6+
const ordinaryStrings = {
7+
tab: 'specs',
8+
filter: 'available',
9+
category: 'hardware',
10+
sort: 'newest',
11+
}
12+
const nonLiteralInitialStrings = {
13+
tab: 'specs',
14+
filter: 'available',
15+
category: 'hardware',
16+
sort: 'descending',
17+
}
18+
const jsonInitialStrings = {
19+
filter: 'foo',
20+
notification: 'new',
21+
tab: 'tabular',
22+
empty: '',
23+
}
24+
const emptyStrings = {
25+
first: '',
26+
second: '',
27+
third: '',
28+
fourth: '',
29+
}
30+
const punctuationStrings = {
31+
file: '.env',
32+
path: '/products',
33+
positive: '+1',
34+
priority: '!important',
35+
}
36+
const nonLiteralPrefixStrings = {
37+
first: 'future',
38+
second: 'framework',
39+
third: 'name',
40+
fourth: 'table',
41+
}
42+
const jsonLiteralPrefixStrings = {
43+
first: 'favorite',
44+
second: 'number',
45+
third: 'travel',
46+
fourth: 'nullish',
47+
}
48+
const jsonLiteralWordStrings = {
49+
truthy: 'true_value',
50+
falsy: 'false_value',
51+
nullable: 'null_value',
52+
}
53+
const jsonLiteralBoundaryStrings = {
54+
truthy: 'true-value',
55+
falsy: 'false/value',
56+
nullable: 'null.value',
57+
}
58+
const jsonStrings = {
59+
number: '123',
60+
boolean: 'true',
61+
object: '{"nested":true}',
62+
array: '[1,2,3]',
63+
}
64+
const mixedValues = {
65+
tab: 'specs',
66+
page: 2,
67+
filters: ['available', 'featured'],
68+
exactPage: '2',
69+
}
70+
let benchmarkSink = 0
71+
72+
expect(defaultStringifySearch(ordinaryStrings)).toBe(
73+
'?tab=specs&filter=available&category=hardware&sort=newest',
74+
)
75+
expect(defaultStringifySearch(nonLiteralInitialStrings)).toBe(
76+
'?tab=specs&filter=available&category=hardware&sort=descending',
77+
)
78+
expect(defaultStringifySearch(jsonInitialStrings)).toBe(
79+
'?filter=foo&notification=new&tab=tabular&empty=',
80+
)
81+
expect(defaultStringifySearch(emptyStrings)).toBe(
82+
'?first=&second=&third=&fourth=',
83+
)
84+
expect(defaultStringifySearch(punctuationStrings)).toBe(
85+
'?file=.env&path=%2Fproducts&positive=%2B1&priority=%21important',
86+
)
87+
expect(defaultStringifySearch(nonLiteralPrefixStrings)).toBe(
88+
'?first=future&second=framework&third=name&fourth=table',
89+
)
90+
expect(defaultStringifySearch(jsonLiteralPrefixStrings)).toBe(
91+
'?first=favorite&second=number&third=travel&fourth=nullish',
92+
)
93+
expect(defaultStringifySearch(jsonLiteralWordStrings)).toBe(
94+
'?truthy=true_value&falsy=false_value&nullable=null_value',
95+
)
96+
expect(defaultStringifySearch(jsonLiteralBoundaryStrings)).toBe(
97+
'?truthy=true-value&falsy=false%2Fvalue&nullable=null.value',
98+
)
99+
expect(defaultStringifySearch(jsonStrings)).toBe(
100+
'?number=%22123%22&boolean=%22true%22&object=%22%7B%5C%22nested%5C%22%3Atrue%7D%22&array=%22%5B1%2C2%2C3%5D%22',
101+
)
102+
expect(defaultStringifySearch(mixedValues)).toBe(
103+
'?tab=specs&page=2&filters=%5B%22available%22%2C%22featured%22%5D&exactPage=%222%22',
104+
)
105+
106+
function stringifyBatch(search: Record<string, unknown>) {
107+
let size = 0
108+
for (let index = 0; index < iterations; index++) {
109+
size += defaultStringifySearch(search).length
110+
}
111+
benchmarkSink = size
112+
}
113+
114+
describe('default search serialization', () => {
115+
bench('ordinary string values', () => {
116+
stringifyBatch(ordinaryStrings)
117+
})
118+
119+
bench('ordinary strings outside JSON-literal initials', () => {
120+
stringifyBatch(nonLiteralInitialStrings)
121+
})
122+
123+
bench('ordinary strings with JSON-literal initials', () => {
124+
stringifyBatch(jsonInitialStrings)
125+
})
126+
127+
bench('empty string values', () => {
128+
stringifyBatch(emptyStrings)
129+
})
130+
131+
bench('ordinary strings with non-JSON punctuation starts', () => {
132+
stringifyBatch(punctuationStrings)
133+
})
134+
135+
bench('ordinary f/n/t words outside JSON-literal prefixes', () => {
136+
stringifyBatch(nonLiteralPrefixStrings)
137+
})
138+
139+
bench('application words with JSON-literal prefixes', () => {
140+
stringifyBatch(jsonLiteralPrefixStrings)
141+
})
142+
143+
bench('application words with complete JSON-literal prefixes', () => {
144+
stringifyBatch(jsonLiteralWordStrings)
145+
})
146+
147+
bench('JSON-literal prefixes followed by punctuation', () => {
148+
stringifyBatch(jsonLiteralBoundaryStrings)
149+
})
150+
151+
bench('JSON-compatible string values', () => {
152+
stringifyBatch(jsonStrings)
153+
})
154+
155+
bench('mixed application values', () => {
156+
stringifyBatch(mixedValues)
157+
})
158+
})
159+
160+
void benchmarkSink

‎packages/router-core/tests/searchParams.test.ts‎

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1-
import { describe, expect, test } from 'vitest'
2-
import { defaultParseSearch, defaultStringifySearch } from '../src'
1+
import { describe, expect, test, vi } from 'vitest'
2+
import {
3+
defaultParseSearch,
4+
defaultStringifySearch,
5+
stringifySearchWith,
6+
} from '../src'
37

48
describe('Search Params serialization and deserialization', () => {
59
/*
@@ -47,6 +51,64 @@ describe('Search Params serialization and deserialization', () => {
4751
expect(defaultParseSearch(str)).toEqual({ foo: 'bar' })
4852
})
4953

54+
test.each([
55+
'false',
56+
'-1',
57+
'"quoted"',
58+
' true ',
59+
'true ',
60+
'false\t',
61+
'null\r\n',
62+
'\tfalse',
63+
'\nnull',
64+
'\r1',
65+
' ',
66+
'雪',
67+
'"雪"',
68+
])('preserves JSON-compatible string %j as a string', (value) => {
69+
const str = defaultStringifySearch({ value })
70+
expect(defaultParseSearch(str)).toEqual({ value })
71+
})
72+
73+
test('uses custom parsers for ordinary strings', () => {
74+
const stringify = stringifySearchWith(JSON.stringify, (value) => {
75+
if (value === 'word') {
76+
return value
77+
}
78+
throw new Error('not parseable')
79+
})
80+
81+
expect(stringify({ value: 'word' })).toEqual('?value=%22word%22')
82+
})
83+
84+
test('skips JSON.parse for strings that cannot be JSON', () => {
85+
const parseSpy = vi.spyOn(JSON, 'parse')
86+
try {
87+
const stringify = stringifySearchWith(JSON.stringify, JSON.parse)
88+
89+
expect(
90+
stringify({
91+
empty: '',
92+
filter: 'foo',
93+
future: 'future',
94+
name: 'name',
95+
notification: 'new',
96+
tab: 'tabular',
97+
topic: 'topic',
98+
unicode: '雪',
99+
}),
100+
).toEqual(
101+
'?empty=&filter=foo&future=future&name=name&notification=new&tab=tabular&topic=topic&unicode=%E9%9B%AA',
102+
)
103+
expect(
104+
stringify({ file: '.env', path: '/products', positive: '+1' }),
105+
).toEqual('?file=.env&path=%2Fproducts&positive=%2B1')
106+
expect(parseSpy).not.toHaveBeenCalled()
107+
} finally {
108+
parseSpy.mockRestore()
109+
}
110+
})
111+
50112
test('[edge case] self-reference serializes to "object Object"', () => {
51113
const obj = {} as any
52114
obj.self = obj

0 commit comments

Comments
 (0)