Skip to content

Commit 378f856

Browse files
committed
optimize: avoid using next when only one key existing.
1 parent becf78f commit 378f856

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

lib/resty/roundrobin.lua

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,22 +35,25 @@ local function get_gcd(nodes)
3535
return error("empty nodes")
3636
end
3737

38+
local only_key = first_id
3839
local gcd = max_weight
3940
for id, weight in next, nodes, first_id do
41+
only_key = nil
4042
gcd = _gcd(gcd, weight)
4143
max_weight = weight > max_weight and weight or max_weight
4244
end
4345

44-
return gcd, max_weight
46+
return only_key, gcd, max_weight
4547
end
4648

4749

4850
function _M.new(_, nodes)
4951
local newnodes = copy(nodes)
50-
local gcd, max_weight = get_gcd(newnodes)
52+
local only_key, gcd, max_weight = get_gcd(newnodes)
5153

5254
local self = {
5355
nodes = newnodes, -- it's safer to copy one
56+
only_key = only_key,
5457
max_weight = max_weight,
5558
gcd = gcd,
5659
cw = max_weight,
@@ -62,7 +65,7 @@ end
6265

6366
function _M.reinit(self, nodes)
6467
local newnodes = copy(nodes)
65-
self.gcd, self.max_weight = get_gcd(newnodes)
68+
self.only_key, self.gcd, self.max_weight = get_gcd(newnodes)
6669

6770
self.nodes = newnodes
6871
self.last_id = nil
@@ -75,7 +78,7 @@ local function _delete(self, id)
7578

7679
nodes[id] = nil
7780

78-
self.gcd, self.max_weight = get_gcd(nodes)
81+
self.only_key, self.gcd, self.max_weight = get_gcd(nodes)
7982

8083
if id == self.last_id then
8184
self.last_id = nil
@@ -103,7 +106,7 @@ local function _decr(self, id, weight)
103106

104107
nodes[id] = old_weight - weight
105108

106-
self.gcd, self.max_weight = get_gcd(nodes)
109+
self.only_key, self.gcd, self.max_weight = get_gcd(nodes)
107110

108111
if self.cw > self.max_weight then
109112
self.cw = self.max_weight
@@ -118,7 +121,7 @@ local function _incr(self, id, weight)
118121

119122
nodes[id] = (nodes[id] or 0) + weight
120123

121-
self.gcd, self.max_weight = get_gcd(nodes)
124+
self.only_key, self.gcd, self.max_weight = get_gcd(nodes)
122125
end
123126
_M.incr = _incr
124127

@@ -141,6 +144,11 @@ end
141144

142145

143146
local function find(self)
147+
local only_key = self.only_key
148+
if only_key then
149+
return only_key
150+
end
151+
144152
local nodes = self.nodes
145153
local last_id, cw, weight = self.last_id, self.cw
146154

0 commit comments

Comments
 (0)