You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@apisix.apache.org by me...@apache.org on 2020/03/19 00:12:42 UTC

[incubator-apisix] branch master updated: chore: improve the preallocation in deepcopy method (#1298)

This is an automated email from the ASF dual-hosted git repository.

membphis pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-apisix.git


The following commit(s) were added to refs/heads/master by this push:
     new a4509b6  chore: improve the preallocation in deepcopy method (#1298)
a4509b6 is described below

commit a4509b6d9edcc70d124e7ee0cb736438c8bc4d04
Author: 罗泽轩 <sp...@gmail.com>
AuthorDate: Thu Mar 19 08:12:33 2020 +0800

    chore: improve the preallocation in deepcopy method (#1298)
---
 lua/apisix/core/table.lua |  6 +++++-
 t/core/table.t            | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 37 insertions(+), 1 deletion(-)

diff --git a/lua/apisix/core/table.lua b/lua/apisix/core/table.lua
index f222789..0fc64ac 100644
--- a/lua/apisix/core/table.lua
+++ b/lua/apisix/core/table.lua
@@ -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
diff --git a/t/core/table.t b/t/core/table.t
index 428608f..59c8875 100644
--- a/t/core/table.t
+++ b/t/core/table.t
@@ -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]