Perf: micro optmize trie

This commit is contained in:
SukkaW 2024-09-23 17:08:33 +08:00
parent af8086f25a
commit 428f30574c

View File

@ -92,19 +92,20 @@ export const createTrie = <Meta = any>(from?: string[] | Set<string> | null, smo
const add = smolTree const add = smolTree
? (suffix: string, meta?: Meta): void => { ? (suffix: string, meta?: Meta): void => {
let node: TrieNode<Meta> = root; let node: TrieNode<Meta> = root;
let curNodeChildren: Map<string, TrieNode<Meta>> = node[2];
const onToken = (token: string) => { const onToken = (token: string) => {
if (node[2].has(token)) { curNodeChildren = node[2];
node = node[2].get(token)!; if (curNodeChildren.has(token)) {
node = curNodeChildren.get(token)!;
// During the adding of `[start]blog|.skk.moe` and find out that there is a `[start].skk.moe` in the trie // During the adding of `[start]blog|.skk.moe` and find out that there is a `[start].skk.moe` in the trie, skip adding the rest of the node
// Dedupe the covered subdomain by skipping if (node[0] && token === '.') {
if (token === '.' && node[0]) {
return true; return true;
} }
} else { } else {
const newNode = createNode(node); const newNode = createNode(node);
node[2].set(token, newNode); curNodeChildren.set(token, newNode);
node = newNode; node = newNode;
} }
@ -176,9 +177,9 @@ export const createTrie = <Meta = any>(from?: string[] | Set<string> | null, smo
for (let i = tokens.length - 1; i >= 0; i--) { for (let i = tokens.length - 1; i >= 0; i--) {
token = tokens[i]; token = tokens[i];
if (token === '') { // if (token === '') {
break; // break;
} // }
parent = node; parent = node;
@ -416,8 +417,9 @@ export const createTrie = <Meta = any>(from?: string[] | Set<string> | null, smo
if (tokens[0] === '.') { if (tokens[0] === '.') {
// If there is a `[start]sub.example.com` here, remove it // If there is a `[start]sub.example.com` here, remove it
parent[0] = false; parent[0] = false;
// Removing all the child nodes by disconnecting ".", which removes "blog.sub.example.com" // Removing all the child nodes by empty the children
parent[2].delete('.'); // This removes the only child ".", which removes "blog.sub.example.com"
parent[2].clear();
} }
// Trying to whitelist `example.com` when there is already a `.example.com` in the trie // Trying to whitelist `example.com` when there is already a `.example.com` in the trie
@ -425,9 +427,6 @@ export const createTrie = <Meta = any>(from?: string[] | Set<string> | null, smo
if (dotNode) { if (dotNode) {
dotNode[0] = false; dotNode[0] = false;
} }
// if (dotNode?.s === true) {
// dotnode[0] = false;
// }
// return early if not found // return early if not found
if (!node[0]) return; if (!node[0]) return;