Skip to content

Commit

Permalink
perf(router/trie-router): optimize 2x faster
Browse files Browse the repository at this point in the history
  • Loading branch information
EdamAme-x committed Dec 6, 2024
1 parent 50ff212 commit beaafe5
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions src/router/trie-router/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ type HandlerParamsSet<T> = HandlerSet<T> & {
params: Record<string, string>
}

const emptyParams = Object.create(null)
const optimizedEmptyParams = (() => {
const E = function () {}

Check failure on line 18 in src/router/trie-router/node.ts

View workflow job for this annotation

GitHub Actions / Main

Unexpected empty function
E.prototype = emptyParams
return E
})() as unknown as { new (): any }

Check warning on line 21 in src/router/trie-router/node.ts

View workflow job for this annotation

GitHub Actions / Main

Unexpected any. Specify a different type

export class Node<T> {
#methods: Record<string, HandlerSet<T>>[]

Expand Down Expand Up @@ -90,7 +97,7 @@ export class Node<T> {
const handlerSet = (m[method] || m[METHOD_NAME_ALL]) as HandlerParamsSet<T>
const processedSet: Record<number, boolean> = {}
if (handlerSet !== undefined) {
handlerSet.params = Object.create(null)
handlerSet.params = new optimizedEmptyParams()
for (let i = 0, len = handlerSet.possibleKeys.length; i < len; i++) {
const key = handlerSet.possibleKeys[i]
const processed = processedSet[handlerSet.score]
Expand All @@ -107,7 +114,7 @@ export class Node<T> {

search(method: string, path: string): [[T, Params][]] {
const handlerSets: HandlerParamsSet<T>[] = []
this.#params = Object.create(null)
this.#params = new optimizedEmptyParams()

// eslint-disable-next-line @typescript-eslint/no-this-alias
const curNode: Node<T> = this
Expand All @@ -129,17 +136,10 @@ export class Node<T> {
// '/hello/*' => match '/hello'
if (nextNode.#children['*']) {
handlerSets.push(
...this.#getHandlerSets(
nextNode.#children['*'],
method,
node.#params,
Object.create(null)
)
...this.#getHandlerSets(nextNode.#children['*'], method, node.#params, emptyParams)
)
}
handlerSets.push(
...this.#getHandlerSets(nextNode, method, node.#params, Object.create(null))
)
handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params, emptyParams))
} else {
tempNodes.push(nextNode)
}
Expand All @@ -155,9 +155,7 @@ export class Node<T> {
if (pattern === '*') {
const astNode = node.#children['*']
if (astNode) {
handlerSets.push(
...this.#getHandlerSets(astNode, method, node.#params, Object.create(null))
)
handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params, emptyParams))
tempNodes.push(astNode)
}
continue
Expand Down

0 comments on commit beaafe5

Please sign in to comment.