chore: improve the preallocation in deepcopy method (#1298)

This commit is contained in:
罗泽轩 2020-03-19 08:12:33 +08:00 committed by GitHub
parent fc948f9578
commit a4509b6d9e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 1 deletions

View File

@ -71,7 +71,11 @@ local function deepcopy(orig)
return orig
end
local copy = new_tab(0, nkeys(orig))
-- If the array-like table contains nil in the middle,
-- the len might be smaller than the expected.
-- But it doesn't affect the correctness.
local len = #orig
local copy = new_tab(len, nkeys(orig) - len)
for orig_key, orig_value in pairs(orig) do
copy[orig_key] = deepcopy(orig_value)
end

View File

@ -45,3 +45,35 @@ encode: ["first","a",1,true]
encode: ["a",1,true,true]
--- no_error_log
[error]
=== TEST 2: deepcopy
--- config
location /t {
content_by_lua_block {
local core = require("apisix.core")
local deepcopy = core.table.deepcopy
local cases = {
{t = {1, 2, a = {2, 3}}},
{t = {{a = b}, 2, true}},
{t = {{a = b}, {{a = c}, {}, 1}, true}},
}
for _, case in ipairs(cases) do
local t = case.t
local actual = core.json.encode(deepcopy(t))
local expect = core.json.encode(t)
if actual ~= expect then
ngx.say("expect ", expect, ", actual ", actual)
return
end
end
ngx.say("ok")
}
}
--- request
GET /t
--- response_body
ok
--- no_error_log
[error]