perf(router): improve performance of router (#3526)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* perf(router): improve performance of router * coverage
authored by EdamAmex · committed by GitHub · parent 234b083 · Browse files · 6 files·+123 added−105 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+123 added−105 removed
- tests:+13 added−0 removed
- other:+110 added−105 removed
Provenance
- Commit
10a5e65- Tree
d4ed9f7- Author
EdamAmex <121654029+EdamAme-x@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
234b083
6 files changed+123 added−105 removed
modified:src/router/linear-router/router.test.ts+13 added
47 unmodified lines48495051525354555657585960616263646547 unmodified lines expect(res.length).toBe(1) expect(res[0][0]).toBe('GET /book') }) })
describe('Skip part', () => { const router = new LinearRouter<string>()
beforeEach(() => { router.add('GET', '/products/:id{d+}', 'GET /products/:id{d+}') })
it('GET /products/list', () => { const [res] = router.match('GET', '/products/list') expect(res.length).toBe(0) }) })})modified:src/router/linear-router/router.ts+91 added-85 removed
11 unmodified lines12131415161718161718192021222324252627282526272829303132333435362930313233394041344344454647483536373839405051525354555641424344454647484950515253545556575859605960616261626364656667646866676869706970717273727374757674757677787978798081828081828384858485868788899091929394959697989986878889909192939495969798991001011021031021041051061071081041051061091081091101111121101111121131141151161171141151181171181191191201211221231241251261271221281241251261291301311321331341351362 unmodified lines11 unmodified lines name: string = 'LinearRouter' routes: [string, string, T][] = []
add(method: string, path: string, handler: T) { ;(checkOptionalParameter(path) || [path]).forEach((p) => { this.routes.push([method, p, handler]) }) for ( let i = 0, paths = checkOptionalParameter(path) || [path], len = paths.length; i < len; i++ ) { this.routes.push([method, paths[i], handler]) } }
match(method: string, path: string): Result<T> { const handlers: [T, Params][] = [] ROUTES_LOOP: for (let i = 0, len = this.routes.length; i < len; i++) { const [routeMethod, routePath, handler] = this.routes[i] if (routeMethod !== method && routeMethod !== METHOD_NAME_ALL) { continue } if (routePath === '*' || routePath === '/*') { handlers.push([handler, emptyParams]) continue }
const hasStar = routePath.indexOf('*') !== -1 const hasLabel = routePath.indexOf(':') !== -1 if (!hasStar && !hasLabel) { if (routePath === path || routePath + '/' === path) { if (routeMethod === method || routeMethod === METHOD_NAME_ALL) { if (routePath === '*' || routePath === '/*') { handlers.push([handler, emptyParams]) continue } } else if (hasStar && !hasLabel) { const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 42 const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe)
const lastIndex = parts.length - 1 for (let j = 0, pos = 0, len = parts.length; j < len; j++) { const part = parts[j] const index = path.indexOf(part, pos) if (index !== pos) { continue ROUTES_LOOP const hasStar = routePath.indexOf('*') !== -1 const hasLabel = routePath.indexOf(':') !== -1 if (!hasStar && !hasLabel) { if (routePath === path || routePath + '/' === path) { handlers.push([handler, emptyParams]) } pos += part.length if (j === lastIndex) { if ( !endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47) ) { } else if (hasStar && !hasLabel) { const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 42 const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe)
const lastIndex = parts.length - 1 for (let j = 0, pos = 0, len = parts.length; j < len; j++) { const part = parts[j] const index = path.indexOf(part, pos) if (index !== pos) { continue ROUTES_LOOP } pos += part.length if (j === lastIndex) { if ( !endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47) ) { continue ROUTES_LOOP } } else { const index = path.indexOf('/', pos) if (index === -1) { continue ROUTES_LOOP } else { const index = path.indexOf('/', pos) if (index === -1) { continue ROUTES_LOOP } pos = index } pos = index } } handlers.push([handler, emptyParams]) } else if (hasLabel && !hasStar) { const params: Record<string, string> = Object.create(null) const parts = routePath.match(splitPathRe) as string[] handlers.push([handler, emptyParams]) } else if (hasLabel && !hasStar) { const params: Record<string, string> = Object.create(null) const parts = routePath.match(splitPathRe) as string[]
const lastIndex = parts.length - 1 for (let j = 0, pos = 0, len = parts.length; j < len; j++) { if (pos === -1 || pos >= path.length) { continue ROUTES_LOOP } const lastIndex = parts.length - 1 for (let j = 0, pos = 0, len = parts.length; j < len; j++) { if (pos === -1 || pos >= path.length) { continue ROUTES_LOOP }
const part = parts[j] if (part.charCodeAt(1) === 58) { // /:label let name = part.slice(2) let value const part = parts[j] if (part.charCodeAt(1) === 58) { // /:label let name = part.slice(2) let value
if (name.charCodeAt(name.length - 1) === 125) { // :label{pattern} const openBracePos = name.indexOf('{') const pattern = name.slice(openBracePos + 1, -1) const restPath = path.slice(pos + 1) const match = new RegExp(pattern, 'd').exec(restPath) as RegExpMatchArrayWithIndices if (!match || match.indices[0][0] !== 0 || match.indices[0][1] === 0) { continue ROUTES_LOOP } name = name.slice(0, openBracePos) value = restPath.slice(...match.indices[0]) pos += match.indices[0][1] + 1 } else { let endValuePos = path.indexOf('/', pos + 1) if (endValuePos === -1) { if (pos + 1 === path.length) { if (name.charCodeAt(name.length - 1) === 125) { // :label{pattern} const openBracePos = name.indexOf('{') const pattern = name.slice(openBracePos + 1, -1) const restPath = path.slice(pos + 1) const match = new RegExp(pattern, 'd').exec(restPath) as RegExpMatchArrayWithIndices if (!match || match.indices[0][0] !== 0 || match.indices[0][1] === 0) { continue ROUTES_LOOP } name = name.slice(0, openBracePos) value = restPath.slice(...match.indices[0]) pos += match.indices[0][1] + 1 } else { let endValuePos = path.indexOf('/', pos + 1) if (endValuePos === -1) { if (pos + 1 === path.length) { continue ROUTES_LOOP } endValuePos = path.length endValuePos = path.length } value = path.slice(pos + 1, endValuePos) pos = endValuePos } value = path.slice(pos + 1, endValuePos) pos = endValuePos }
params[name] ||= value as string } else { const index = path.indexOf(part, pos) if (index !== pos) { continue ROUTES_LOOP params[name] ||= value as string } else { const index = path.indexOf(part, pos) if (index !== pos) { continue ROUTES_LOOP } pos += part.length } pos += part.length }
if (j === lastIndex) { if (pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) { continue ROUTES_LOOP if (j === lastIndex) { if ( pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47) ) { continue ROUTES_LOOP } } } }
handlers.push([handler, params]) } else if (hasLabel && hasStar) { throw new UnsupportedPathError() handlers.push([handler, params]) } else if (hasLabel && hasStar) { throw new UnsupportedPathError() } } }
return [handlers]2 unmodified linesmodified:src/router/pattern-router/router.ts+4 added-2 removed
38 unmodified lines39 40 match(method: string, path: string): Result<T> {41 const handlers: [T, Params][] = []42 43- for (const [pattern, routeMethod, handler] of this.routes) {44- if (routeMethod === METHOD_NAME_ALL || routeMethod === method) {43+ for (let i = 0, len = this.routes.length; i < len; i++) {44+ const [pattern, routeMethod, handler] = this.routes[i]45+46+ if (routeMethod === method || routeMethod === METHOD_NAME_ALL) {47 const match = pattern.exec(path)48 if (match) {49 handlers.push([handler, match.groups || Object.create(null)])50 }6 unmodified linesmodified:src/router/smart-router/router.ts+3 added-3 removed
28 unmodified lines29 let res30 for (; i < len; i++) {31 const router = routers[i]32 try {33- routes.forEach((args) => {34- router.add(...args)35- })33+ for (let i = 0, len = routes.length; i < len; i++) {34+ router.add(...routes[i])35+ }36 res = router.match(method, path)37 } catch (e) {38 if (e instanceof UnsupportedPathError) {39 continue29 unmodified linesmodified:src/router/trie-router/node.ts+10 added-13 removed
5 unmodified lines6 type HandlerSet<T> = {7 handler: T8 possibleKeys: string[]9 score: number10- name: string // For debug10 }11 12 type HandlerParamsSet<T> = HandlerSet<T> & {13 params: Record<string, string>4 unmodified lines18 19 children: Record<string, Node<T>>20 patterns: Pattern[]21 order: number = 023- name: string22 params: Record<string, string> = Object.create(null)23 24 constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {25 this.children = children || Object.create(null)26 this.methods = []29- this.name = ''27 if (method && handler) {28 const m: Record<string, HandlerSet<T>> = Object.create(null)32- m[method] = { handler, possibleKeys: [], score: 0, name: this.name }29+ m[method] = { handler, possibleKeys: [], score: 0 }30 this.methods = [m]31 }32 this.patterns = []33 }34 35 insert(method: string, path: string, handler: T): Node<T> {39- this.name = `${method} ${path}`36 this.order = ++this.order37 38 // eslint-disable-next-line @typescript-eslint/no-this-alias39 let curNode: Node<T> = this31 unmodified lines71 72 const handlerSet: HandlerSet<T> = {73 handler,74 possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),79- name: this.name,75 score: this.order,76 }77 78 m[method] = handlerSet15 unmodified lines94 const handlerSet = (m[method] || m[METHOD_NAME_ALL]) as HandlerParamsSet<T>95 const processedSet: Record<string, boolean> = Object.create(null)96 if (handlerSet !== undefined) {97 handlerSet.params = Object.create(null)103- handlerSet.possibleKeys.forEach((key) => {104- const processed = processedSet[handlerSet.name]98+ for (let i = 0, len = handlerSet.possibleKeys.length; i < len; i++) {99+ const key = handlerSet.possibleKeys[i]100+ const processed = processedSet[handlerSet.score]101 handlerSet.params[key] =102 params[key] && !processed ? params[key] : nodeParams[key] ?? params[key]107- processedSet[handlerSet.name] = true108- })103+ processedSet[handlerSet.score] = true104+ }105+106 handlerSets.push(handlerSet)107 }108 }109 return handlerSets18 unmodified lines128 const nextNode = node.children[part]129 130 if (nextNode) {131 nextNode.params = node.params135- if (isLast === true) {132+ if (isLast) {133 // '/hello/*' => match '/hello'134 if (nextNode.children['*']) {135 handlerSets.push(136 ...this.gHSets(nextNode.children['*'], method, node.params, Object.create(null))36 unmodified lines173 handlerSets.push(...this.gHSets(child, method, node.params, params))174 continue175 }176 180- if (matcher === true || (matcher instanceof RegExp && matcher.test(part))) {177+ if (matcher === true || matcher.test(part)) {178 if (typeof key === 'string') {179 params[name] = part183- if (isLast === true) {180+ if (isLast) {181 handlerSets.push(...this.gHSets(child, method, params, node.params))182 if (child.children['*']) {183 handlerSets.push(...this.gHSets(child.children['*'], method, params, node.params))184 }18 unmodified linesmodified:src/router/trie-router/router.ts+2 added-2 removed
11 unmodified lines12 13 add(method: string, path: string, handler: T) {14 const results = checkOptionalParameter(path)15 if (results) {16- for (const p of results) {17- this.node.insert(method, p, handler)16+ for (let i = 0, len = results.length; i < len; i++) {17+ this.node.insert(method, results[i], handler)18 }19 return20 }21 7 unmodified lines