Default to performance-aware coding for hot paths (proxy routing, request parsing, metrics/serialization, and request body handling):
tb_nkeys() on request-critical structures; prefer constant-time checks (e.g., next()-based) or use existing router-provided capture counts.ngx.ctx, ngx.var.http_content_type, ngx.header[name]) over higher-level helpers when the value is already available.Example (constant-time capture check + localizing next):
local next_ = next
-- captures = { [0]=full_path, [1]=cap1, ... }
local function has_uri_captured(captures)
if not captures then return nil end
-- constant-time check for any key other than [0]
if captures[1] then
return captures
end
return next_(captures, 0) and captures or nil
end
Example (reuse metatable outside the hot function):
local payload_mt = {
__newindex = function(t, k, v)
-- set dot-path values
end,
}
local function build_payload(template_payload)
return setmetatable(template_payload, payload_mt)
end
If you’re unsure whether a change is beneficial, treat it as a performance work item: profile/flamegraph or microbenchmark it under realistic inputs before merging.