From 19805d74124b030e9b95bf14784723f40c8da521 Mon Sep 17 00:00:00 2001 From: Luis Alvarez D Date: Wed, 4 Nov 2026 15:40:54 -0500 Subject: [PATCH] perf(router): speed up interpreter lookups - slice trailing catch-all values from the lookup path instead of rebuilding them from segments - drop the shift copy in splitPath - initialize node fields together so lookups see one hidden class - index getMatchParams and fast-path a single plain param Measured with an interleaved before/after benchmark on Bun and Node: dynamic, wildcard, mixed, optional, and scale-1000 lookups improve 21-64% on Bun and 10-19% on Node. Compiled lookups are unchanged. Tests: 4019 passed, tsc, oxlint and oxfmt clean. Bundle budget updated. --- src/_match.ts | 25 ++++++++++++++++++++----- src/context.ts | 3 ++- src/node.ts | 15 +++++++++++++++ src/operations/add.ts | 21 +++++++++++++++------ src/operations/find-all.ts | 5 ++++- src/operations/find.ts | 2 +- src/types.ts | 5 +++++ test/bench/bundle.test.ts | 7 +++++-- 8 files changed, 67 insertions(+), 16 deletions(-) create mode 100644 src/node.ts diff --git a/src/_match.ts b/src/_match.ts index 96d1cdb..07e0a0e 100644 --- a/src/_match.ts +++ b/src/_match.ts @@ -60,9 +60,7 @@ export function normalizePath(path: string): string { * segments. Empty segments are kept: `/a/` is `["a", ""]` (#209). */ export function splitPath(path: string): string[] { - const s = path.split("/"); - s.shift(); - return s; + return path.split("/").slice(1); } /** @@ -120,18 +118,35 @@ export function getMatchParams( paramsMap: ParamsIndexMap, suffix?: [number, number], slash?: boolean, + path?: string, + catchAllOffset?: number, ): MatchedRoute["params"] { const params = new NullProtoObj(); + if (paramsMap.length === 1 && !suffix) { + const map = paramsMap[0]; + const index = map[0]; + if (index >= 0 && typeof map[1] === "string" && !map[2] && !map[5]) { + params[map[1]] = segments[index]; + return params; + } + } // Segments after a `**` are counted from the end of the path const end = suffix ? segments.length - suffix[1] : segments.length; - for (const [index, name, optional, , , join] of paramsMap) { + for (let p = 0; p < paramsMap.length; p++) { + const map = paramsMap[p]; + const index = map[0]; + const name = map[1]; + const optional = map[2]; + const join = map[5]; // A bare `**` (`~index` is where it starts; negative for the other // params) over zero segments is unset; a trailing `*` there too, unless // the lookup path had a trailing slash (`slash`): `""` if (~index >= end && (optional || !slash)) continue; const segment = index < 0 - ? segments.slice(~index, end).join("/") + ? catchAllOffset !== undefined && path !== undefined + ? path.slice(catchAllOffset) + : segments.slice(~index, end).join("/") : segments[suffix && index > suffix[0] ? index - suffix[0] - 1 + end : index]; if (typeof name === "string") { setParam(params, name, segment, join); diff --git a/src/context.ts b/src/context.ts index e017dc5..c683015 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,3 +1,4 @@ +import { createNode } from "./node.ts"; import { NullProtoObj } from "./object.ts"; import type { RouterContext } from "./types.ts"; @@ -6,7 +7,7 @@ import type { RouterContext } from "./types.ts"; */ export function createRouter(): RouterContext { const ctx: RouterContext = { - root: { key: "" }, + root: createNode(""), static: new NullProtoObj(), }; return ctx; diff --git a/src/node.ts b/src/node.ts new file mode 100644 index 0000000..1b8e0ca --- /dev/null +++ b/src/node.ts @@ -0,0 +1,15 @@ +import type { Node } from "./types.ts"; + +/** All fields are set so nodes keep one hidden class. */ +export function createNode(key: string): Node { + return { + key, + static: undefined, + param: undefined, + wildcard: undefined, + suffix: undefined, + hasSuffix: undefined, + hasRegexParam: undefined, + methods: undefined, + }; +} diff --git a/src/operations/add.ts b/src/operations/add.ts index b8eed7f..c051f52 100644 --- a/src/operations/add.ts +++ b/src/operations/add.ts @@ -19,6 +19,7 @@ import { } from "../_pattern.ts"; import { getParamRegexp, linearRegExp } from "../_segment-regexp.ts"; import { createRouter } from "../context.ts"; +import { createNode } from "../node.ts"; import { NullProtoObj } from "../object.ts"; import type { Node, RouterContext, ParamsIndexMap } from "../types.ts"; @@ -211,6 +212,9 @@ function _insert( let wildcardIndex = -1; // Nodes on the way to the catch-all, flagged `hasSuffix` for a suffix route const trail: Node[] | undefined = star ? [] : undefined; + // Catch-all value offset when its prefix is static (see `getMatchParams`) + let catchAllOffset = -1; + let prefixLength = 1; for (let i = 0; i < segments.length; i++) { let segment = segments[i]; @@ -223,7 +227,7 @@ function _insert( } trail?.push(node); if (!node.wildcard) { - node.wildcard = { key: "**" }; + node.wildcard = createNode("**"); } node = node.wildcard; // A `*` takes one segment or more (or, last, none: see `matchesZero`), @@ -236,6 +240,9 @@ function _insert( // `getMatchParams`), so that name is taken. The `**` of a split `*` is // part of its capture: its number (taken by the piece before it, if // any), no `_` alias. + if (join === -1 && i === segments.length - 1 && paramsMap.length === 0) { + catchAllOffset = prefixLength; + } paramsMap.push([ -(i + 1), i === join @@ -268,7 +275,7 @@ function _insert( } else { trail?.push(node); if (!node.param) { - node.param = { key: "*" }; + node.param = createNode("*"); } node = node.param; } @@ -315,12 +322,13 @@ function _insert( suffix.push(segment); continue; } + prefixLength += segment.length + 1; trail?.push(node); const child = node.static?.[segment]; if (child) { node = child; } else { - const staticNode = { key: segment }; + const staticNode = createNode(segment); if (!node.static) { node.static = new NullProtoObj(); } @@ -333,13 +341,13 @@ function _insert( for (const n of trail!) { n.hasSuffix = true; } - node = node.suffix ??= { key: "" }; + node = node.suffix ??= createNode(""); for (let j = suffix.length - 1; j >= 0; j--) { const edge = suffix[j]; if (edge === 1) { - node = node.param ??= { key: "*" }; + node = node.param ??= createNode("*"); } else { - node = (node.static ??= new NullProtoObj())[edge] ??= { key: edge }; + node = (node.static ??= new NullProtoObj())[edge] ??= createNode(edge); } } } @@ -354,6 +362,7 @@ function _insert( paramsMap: hasParams ? paramsMap : undefined, route: route ?? key, suffix: suffix && [wildcardIndex, suffix.length], + catchAllOffset: catchAllOffset >= 0 ? catchAllOffset : undefined, variants, // Within half a weight point (`getParamRegexp` ranks a segment by // +-2^31 at most) diff --git a/src/operations/find-all.ts b/src/operations/find-all.ts index d2ea14f..d28c5f3 100644 --- a/src/operations/find-all.ts +++ b/src/operations/find-all.ts @@ -49,7 +49,10 @@ export function findAllRoutes( const params = opts?.params !== false; return matches.map((m) => params && m.paramsMap - ? { data: m.data, params: getMatchParams(segments, m.paramsMap, m.suffix, slash) } + ? { + data: m.data, + params: getMatchParams(segments, m.paramsMap, m.suffix, slash, path, m.catchAllOffset), + } : { data: m.data }, ); } diff --git a/src/operations/find.ts b/src/operations/find.ts index 3e7fe54..fc20807 100644 --- a/src/operations/find.ts +++ b/src/operations/find.ts @@ -72,7 +72,7 @@ export function findRoute( return { data: match.data, params: match.paramsMap - ? getMatchParams(segments, match.paramsMap, match.suffix, slash) + ? getMatchParams(segments, match.paramsMap, match.suffix, slash, path, match.catchAllOffset) : undefined, }; } diff --git a/src/types.ts b/src/types.ts index 89c6954..e29c1ec 100644 --- a/src/types.ts +++ b/src/types.ts @@ -47,6 +47,11 @@ export type MethodData = { * the path. */ suffix?: [wildcard: number, length: number]; + /** + * Set on a trailing catch-all whose prefix is static: where its value starts + * in the lookup path (leading `/` included). + */ + catchAllOffset?: number; /** * Set on every entry (variant) of an `addRoute` call that registers several * (optional syntax, a `*` inside a segment): a token they share (identity diff --git a/test/bench/bundle.test.ts b/test/bench/bundle.test.ts index 44f5090..1191c1c 100644 --- a/test/bench/bundle.test.ts +++ b/test/bench/bundle.test.ts @@ -248,8 +248,11 @@ describe("benchmark", () => { // +0B raw / +12B gzip: `src/` regrouped by concept (`_pattern.ts`, // `_match.ts`, `_segment-regexp.ts`); the same code in another module // order. - expect(bytes).toBeLessThanOrEqual(15099); // <15.10kb - expect(gzipSize).toBeLessThanOrEqual(6501); // <6.51kb + // +441B raw / +180B gzip: interpreter perf pass (catch-all path slicing, + // `splitPath` without `shift`, stable node shapes, indexed params with a + // single-param fast path). Compiled lookup is unchanged. + expect(bytes).toBeLessThanOrEqual(15560); // <15.56kb + expect(gzipSize).toBeLessThanOrEqual(6700); // <6.70kb }); it("unused exports of the single-file build leave no code behind", async () => {