From 0c5decbeaee7d189e0aa6197668efd0b1a6409c6 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 16 Aug 2026 22:55:46 -0500 Subject: [PATCH] perf(router): skip query parsing when there is no query string MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/http/router.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/http/router.ts b/src/http/router.ts index fdaae6e..8dce901 100644 --- a/src/http/router.ts +++ b/src/http/router.ts @@ -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 { + // 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 = {}; for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;