浏览代码

Perf: micro optmize trie

SukkaW 1 年之前
父节点
当前提交
428f30574c
共有 1 个文件被更改,包括 13 次插入14 次删除
  1. 13 14
      Build/lib/trie.ts

+ 13 - 14
Build/lib/trie.ts

@@ -92,19 +92,20 @@ export const createTrie = <Meta = any>(from?: string[] | Set<string> | null, smo
   const add = smolTree
     ? (suffix: string, meta?: Meta): void => {
       let node: TrieNode<Meta> = root;
+      let curNodeChildren: Map<string, TrieNode<Meta>> = node[2];
 
       const onToken = (token: string) => {
-        if (node[2].has(token)) {
-          node = node[2].get(token)!;
+        curNodeChildren = node[2];
+        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
-          // Dedupe the covered subdomain by skipping
-          if (token === '.' && node[0]) {
+          // 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
+          if (node[0] && token === '.') {
             return true;
           }
         } else {
           const newNode = createNode(node);
-          node[2].set(token, newNode);
+          curNodeChildren.set(token, 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--) {
       token = tokens[i];
 
-      if (token === '') {
-        break;
-      }
+      // if (token === '') {
+      //   break;
+      // }
 
       parent = node;
 
@@ -416,8 +417,9 @@ export const createTrie = <Meta = any>(from?: string[] | Set<string> | null, smo
     if (tokens[0] === '.') {
       // If there is a `[start]sub.example.com` here, remove it
       parent[0] = false;
-      // Removing all the child nodes by disconnecting ".", which removes "blog.sub.example.com"
-      parent[2].delete('.');
+      // Removing all the child nodes by empty the children
+      // 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
@@ -425,9 +427,6 @@ export const createTrie = <Meta = any>(from?: string[] | Set<string> | null, smo
     if (dotNode) {
       dotNode[0] = false;
     }
-    // if (dotNode?.s === true) {
-    //   dotnode[0] = false;
-    // }
 
     // return early if not found
     if (!node[0]) return;