Skip to content

Commit 6c4022d

Browse files
optimize: cache the table for sending requests.
1 parent 8641b9f commit 6c4022d

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

lib/resty/redis.lua

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ local tonumber = tonumber
1616
local tostring = tostring
1717
local rawget = rawget
1818
local select = select
19+
local tb_clear = require "table.clear"
1920
--local error = error
2021

2122

@@ -24,7 +25,8 @@ if not ok or type(new_tab) ~= "function" then
2425
new_tab = function (narr, nrec) return {} end
2526
end
2627

27-
28+
local tab_pool_len = 0
29+
local tab_pool = new_tab(16, 0)
2830
local _M = new_tab(0, 55)
2931

3032
_M._VERSION = '0.30'
@@ -59,6 +61,27 @@ local unsub_commands = {
5961
local mt = { __index = _M }
6062

6163

64+
local function get_tab_from_pool()
65+
if tab_pool_len > 0 then
66+
tab_pool_len = tab_pool_len - 1
67+
return tab_pool[tab_pool_len + 1]
68+
end
69+
70+
return new_tab(24, 0) -- one field takes 5 slots
71+
end
72+
73+
74+
local function put_tab_into_pool(tab)
75+
if tab_pool_len >= 32 then
76+
return
77+
end
78+
79+
tb_clear(tab)
80+
tab_pool_len = tab_pool_len + 1
81+
tab_pool[tab_pool_len] = tab
82+
end
83+
84+
6285
function _M.new(self)
6386
local sock, err = tcp()
6487
if not sock then
@@ -305,9 +328,11 @@ end
305328
local function _gen_req(args)
306329
local nargs = #args
307330

308-
local req = new_tab(nargs * 5 + 1, 0)
309-
req[1] = "*" .. nargs .. "\r\n"
310-
local nbits = 2
331+
local req = get_tab_from_pool()
332+
req[1] = "*"
333+
req[2] = nargs
334+
req[3] = "\r\n"
335+
local nbits = 4
311336

312337
for i = 1, nargs do
313338
local arg = args[i]
@@ -355,6 +380,8 @@ local function _do_cmd(self, ...)
355380
-- print("request: ", table.concat(req))
356381

357382
local bytes, err = sock:send(req)
383+
put_tab_into_pool(req)
384+
358385
if not bytes then
359386
return nil, err
360387
end
@@ -625,6 +652,10 @@ function _M.commit_pipeline(self)
625652
end
626653

627654
local bytes, err = sock:send(reqs)
655+
for _, req in ipairs(reqs) do
656+
put_tab_into_pool(req)
657+
end
658+
628659
if not bytes then
629660
return nil, err
630661
end

0 commit comments

Comments
 (0)