perf(router): skip query parsing when there is no query string
parseQuery ran on every request. For a URL without a `?` it split the string,
built a URLSearchParams from '', looped zero times and returned {} — three
allocations to arrive at an empty object, on the majority of requests.
92.3ns before, 18.6ns after, in isolation. End to end: -3.1% request latency
over five interleaved rounds.
Only the guard is new. Switching the parse itself to indexOf + slice would drop
another allocation, but it changes what a second `?` in a URL means, and that
is a behaviour question that does not belong in a performance commit.
Found by CPU-profiling the request path rather than guessing. Worth recording
what that profile showed: almost nothing in it is green-tea. Building the
web-standard Request/Response/Headers in undici dominates — appendHeader alone
is 5.2%, Response construction 2.8%, stream state 4.5%, GC 5% — while the only
green-tea frames above 1.5% were mergeInjectedHeaders at 2.6% and this at 1.8%.
The per-request cost of app.fetch is mostly the price of returning a real
Response, not framework logic. mergeInjectedHeaders is the next candidate: it
rebuilds a lowercased Set of the injected header keys on every response, and
those keys are fixed for the life of the app.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
1 file changed
+9
@@ -304,6 +304,15 @@ export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
||||
|
||||
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
||||
export function parseQuery(url: string): Record<string, string> {
|
||||
// Most requests carry no query string, and the work below is not free for them: `split` builds
|
||||
// an array, `new URLSearchParams('')` builds an object, and the loop runs zero times — three
|
||||
// allocations to arrive at `{}`. Measured at 92.3 ns against 18.6 ns for this check.
|
||||
//
|
||||
// Only the guard is new; the parse below is untouched on purpose. Reaching for `indexOf` +
|
||||
// `slice` instead of `split` would also drop an allocation, but it changes what a second `?`
|
||||
// means, and that is a behaviour question rather than a performance one.
|
||||
if (!url.includes('?')) return {};
|
||||
|
||||
const queryString = url.split('?')[1] ?? '';
|
||||
const out: Record<string, string> = {};
|
||||
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
|
||||
|
||||
Reference in new issue
Block a user