Skip to content

Commit

Permalink
perf: avoid #path
Browse files Browse the repository at this point in the history
  • Loading branch information
vm-001 committed Dec 20, 2023
1 parent 4c02274 commit 95330ca
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/resty/trie.lua
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ function TrieNode:traverse(path, ctx)
local node = self
local prefix
local prefix_n
local path_n
local path_n = #path
local idx


Expand All @@ -194,14 +194,15 @@ function TrieNode:traverse(path, ctx)

-- 到这里的 node 节点都是 static
if node.type == TYPES.PARAM then
local i = find(path, "/", 1, true) or #path + 1 -- todo 写一个 while 来实现
local i = find(path, "/", 1, true) or path_n + 1 -- todo 写一个 while 来实现
i = i - 1
if binding_params then
-- todo 参数绑定
end
if i < #path then -- 还没到终点
if i < path_n then -- 还没到终点
if node.children_n > 0 then
path = str_sub(path, i + 1)
path_n = path_n - i
local first_char = str_sub(path, 1, 1)
idx = node.indexs[first_char]
if idx then
Expand All @@ -224,17 +225,17 @@ function TrieNode:traverse(path, ctx)

prefix = node.path
prefix_n = node.path_n
path_n = #path -- path_n 有没有可能可以通过游标去减,而不是每次都 #path?

if path_n > prefix_n then
if starts_with(path, prefix, path_n, prefix_n) then
path = str_sub(path, prefix_n + 1)
path_n = path_n - prefix_n

idx = node.indexs["*"]
if idx then
-- 如果子节点中有 catchall 类型,说明 child 节点是能匹配的
matched_n = matched_n + 1
matched_values[matched_n] = node.children[idx].value -- todo 既然这里已经选中了,为什么不做参数绑定呢?
matched_values[matched_n] = node.children[idx].value
if binding_params then
param_n = param_n + 1
ctx.matched[param_n] = path
Expand Down Expand Up @@ -270,16 +271,17 @@ function TrieNode:traverse(path, ctx)
idx = node.indexs[":"]
if idx then
node = node.children[idx]
local i = find(path, "/", 1, true) or #path + 1 -- todo 写一个 while 来实现
local i = find(path, "/", 1, false) or path_n + 1 -- 为啥写 while 性能比 find 还慢?
i = i - 1
if binding_params then
local param_value = str_sub(path, 1, i)
param_n = param_n + 1
ctx.matched[param_n] = param_value
end
if i < #path then -- 还没到终点
if i < path_n then -- 还没到终点
if node.children_n > 0 then
path = str_sub(path, i + 1)
path_n = path_n - i
first_char = str_sub(path, 1, 1)
idx = node.indexs[first_char]
if idx then
Expand Down Expand Up @@ -322,6 +324,7 @@ function TrieNode:traverse(path, ctx)
if branchs_n > 0 then
node = branchs[branchs_n]
path = paths[branchs_n]
path_n = #path
branchs[branchs_n] = nil
paths[branchs_n] = nil
branchs_n = branchs_n - 1
Expand Down

0 comments on commit 95330ca

Please sign in to comment.