给定一个支持 lua 脚本的单实例 redis。一次调用“mget”和多次调用“get”来检索多个键的值之间是否有性能差异?
从时间复杂度来看,两者的结果是相同的:O(N) = N*O(1)。
但是处理每个命令并将结果解析回 Lua 会产生一定的开销。所以MGET会给你更好的表现。
你可以测量这个。以下脚本接收一系列键,一个调用GET多次,另一个调用MGET.
GET多次调用:
local t0 = redis.call('TIME')
local res = {}
for i = 1,table.getn(KEYS),1 do
res[i] = redis.call('GET', KEYS[i])
end
local t1 = redis.call('TIME')
local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2]
table.insert(res,'Time taken: '..micros..' microseconds')
table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2]))
table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2]))
return res
Run Code Online (Sandbox Code Playgroud)
调用MGET一次:
local t0 = redis.call('TIME')
local res = redis.call('MGET', unpack(KEYS))
local t1 = redis.call('TIME')
local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2]
table.insert(res,'Time taken: '..micros..' microseconds')
table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2]))
table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2]))
return res
Run Code Online (Sandbox Code Playgroud)
GET多次调用需要 51 微秒,而MGET一次调用需要 20 微秒:
> EVAL "local t0 = redis.call('TIME') \n local res = {} \n for i = 1,table.getn(KEYS),1 do \n res[i] = redis.call('GET', KEYS[i]) \n end \n local t1 = redis.call('TIME') \n local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2] \n table.insert(res,'Time taken: '..micros..' microseconds') \n table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2])) \n table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2])) \n return res" 10 key:1 key:2 key:3 key:4 key:5 key:6 key:7 key:8 key:9 key:10
1) "value:1"
2) "value:2"
3) "value:3"
4) "value:4"
5) "value:5"
6) "value:6"
7) "value:7"
8) "value:8"
9) "value:9"
10) "value:10"
11) "Time taken: 51 microseconds"
12) "T0: 1581664542637472"
13) "T1: 1581664542637523"
> EVAL "local t0 = redis.call('TIME') \n local res = redis.call('MGET', unpack(KEYS)) \n local t1 = redis.call('TIME') \n local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2] \n table.insert(res,'Time taken: '..micros..' microseconds') \n table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2])) \n table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2])) \n return res" 10 key:1 key:2 key:3 key:4 key:5 key:6 key:7 key:8 key:9 key:10
1) "value:1"
2) "value:2"
3) "value:3"
4) "value:4"
5) "value:5"
6) "value:6"
7) "value:7"
8) "value:8"
9) "value:9"
10) "value:10"
11) "Time taken: 20 microseconds"
12) "T0: 1581664667232092"
13) "T1: 1581664667232112"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4331 次 |
| 最近记录: |