Skip to content

Commit

Permalink
perf: reduce tst built time (#2517)
Browse files Browse the repository at this point in the history
  • Loading branch information
tsctx authored Dec 12, 2023
1 parent d434bb7 commit 3fd7bf3
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions lib/core/tree.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
'use strict'

const { wellknownHeaderNames } = require('./constants')
const {
wellknownHeaderNames,
headerNameLowerCasedRecord
} = require('./constants')

class TstNode {
/** @type {any} */
Expand All @@ -16,14 +19,15 @@ class TstNode {
/**
* @param {Uint8Array} key
* @param {any} value
* @param {number} index
*/
constructor (key, value) {
if (key.length === 0) {
constructor (key, value, index) {
if (index === undefined || index >= key.length) {
throw new TypeError('Unreachable')
}
this.code = key[0]
if (key.length > 1) {
this.middle = new TstNode(key.subarray(1), value)
this.code = key[index]
if (key.length !== ++index) {
this.middle = new TstNode(key, value, index)
} else {
this.value = value
}
Expand All @@ -32,31 +36,32 @@ class TstNode {
/**
* @param {Uint8Array} key
* @param {any} value
* @param {number} index
*/
add (key, value) {
if (key.length === 0) {
add (key, value, index) {
if (index === undefined || index >= key.length) {
throw new TypeError('Unreachable')
}
const code = key[0]
const code = key[index]
if (this.code === code) {
if (key.length === 1) {
if (key.length === ++index) {
this.value = value
} else if (this.middle !== null) {
this.middle.add(key.subarray(1), value)
this.middle.add(key, value, index)
} else {
this.middle = new TstNode(key.subarray(1), value)
this.middle = new TstNode(key, value, index)
}
} else if (this.code < code) {
if (this.left !== null) {
this.left.add(key, value)
this.left.add(key, value, index)
} else {
this.left = new TstNode(key, value)
this.left = new TstNode(key, value, index)
}
} else {
if (this.right !== null) {
this.right.add(key, value)
this.right.add(key, value, index)
} else {
this.right = new TstNode(key, value)
this.right = new TstNode(key, value, index)
}
}
}
Expand Down Expand Up @@ -102,9 +107,9 @@ class TernarySearchTree {
* */
insert (key, value) {
if (this.node === null) {
this.node = new TstNode(key, value)
this.node = new TstNode(key, value, 0)
} else {
this.node.add(key, value)
this.node.add(key, value, 0)
}
}

Expand All @@ -119,7 +124,7 @@ class TernarySearchTree {
const tree = new TernarySearchTree()

for (let i = 0; i < wellknownHeaderNames.length; ++i) {
const key = wellknownHeaderNames[i].toLowerCase()
const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]
tree.insert(Buffer.from(key), key)
}

Expand Down

0 comments on commit 3fd7bf3

Please sign in to comment.