0
0
Redisquery~5 mins

Lua vs transactions comparison in Redis - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Lua vs transactions comparison
O(n)
Understanding Time Complexity

We want to understand how the time cost changes when using Lua scripts versus transactions in Redis.

Which method grows faster in execution time as the input size increases?

Scenario Under Consideration

Analyze the time complexity of these two Redis approaches.

-- Lua script example
local vals = redis.call('LRANGE', KEYS[1], 0, -1)
for i, v in ipairs(vals) do
  redis.call('HSET', KEYS[2], v, i)
end

-- Transaction example
MULTI
LRANGE mylist 0 -1
HSET myhash field1 val1
EXEC

The Lua script runs commands inside one script; the transaction groups commands to run atomically.

Identify Repeating Operations

Look for repeated steps that affect time.

  • Primary operation: Loop inside Lua script calling HSET for each list item.
  • How many times: Once per list element (n times).
How Execution Grows With Input

As the list size grows, the Lua script runs more HSET commands in one go.

Input Size (n)Approx. Operations
10About 10 HSET calls inside Lua
100About 100 HSET calls inside Lua
1000About 1000 HSET calls inside Lua

Pattern observation: The Lua script time grows roughly linearly with the number of list items.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in direct proportion to the number of items processed.

Common Mistake

[X] Wrong: "Lua scripts always run instantly no matter the input size."

[OK] Correct: Lua scripts still do work for each item, so time grows with input size.

Interview Connect

Knowing how Lua scripts and transactions scale helps you choose the right tool for efficient Redis operations.

Self-Check

What if the Lua script called multiple Redis commands per list item? How would the time complexity change?