From 3fd7bf3a34f593c7d4fb03e48559755c659d1f1a Mon Sep 17 00:00:00 2001 From: tsctx <91457664+tsctx@users.noreply.github.com> Date: Tue, 12 Dec 2023 22:09:19 +0900 Subject: [PATCH] perf: reduce tst built time (#2517) --- lib/core/tree.js | 43 ++++++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/lib/core/tree.js b/lib/core/tree.js index aa1641d217f..a61de9efbd9 100644 --- a/lib/core/tree.js +++ b/lib/core/tree.js @@ -1,6 +1,9 @@ 'use strict' -const { wellknownHeaderNames } = require('./constants') +const { + wellknownHeaderNames, + headerNameLowerCasedRecord +} = require('./constants') class TstNode { /** @type {any} */ @@ -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 } @@ -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) } } } @@ -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) } } @@ -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) }