Redis - Why is this code SO fast?
snippet in lua

Redis - Why is this code SO fast?

user1488

require 'benchmark'
require 'redis'

redis = Redis.new(host: '127.0.0.1', db: 1)
KEYS = 10_000.times.collect { |i| "KEY#{i}" }
KEYS.each { |key| redis.zadd(key, 0, 'DATA') }

script = " 
local sum = 0
for index, key in pairs(KEYS) do
  sum = sum + redis.call('zcard', key);
end
return sum"

Benchmark.bm do |x|
  x.report { puts KEYS.inject(0) { |sum, key| sum + redis.zcard(key) } }
  x.report do
    client = redis.client
    client.send(:ensure_connected) do
      KEYS.inject(0) { |sum, key| sum + client.process([[:zcard, key]]) { client.read } }
    end.tap { |res| puts res}
  end
  x.report do
    client = redis.client
    client.send(:ensure_connected) do
      connection = client.connection
      socket = connection.instance_variable_get(:@sock)
      KEYS.map do |key|
        command = connection.build_command([:zcard, key])
        # Redis::Connection::Ruby
        socket.write(command) # write to socket, 20% of execution time
        line = socket.gets # read from socket, 80% of execution time
        reply_type = line.slice!(0, 1)
        connection.format_reply(reply_type, line)
      end.inject(:+)
    end.tap { |res| puts res}
  end
  x.report { puts redis.eval(script, KEYS) }
end

# user     system      total        real
# 10000
# 0.480000   0.230000   0.710000 (  0.966610)
# 10000
# 0.510000   0.250000   0.760000 (  1.132668)
# 10000
# 0.500000   0.270000   0.770000 (  1.193521)
# 10000
# 0.030000   0.000000   0.030000 (  0.054858)
# [Finished in 4.923s]