SUNIONSTORE for storing results in Redis - Time & Space Complexity
We want to understand how the time needed to combine sets grows when using SUNIONSTORE in Redis.
Specifically, how does the work change as the sets get bigger?
Analyze the time complexity of the following code snippet.
# Combine two sets and store the result
SUNIONSTORE resultSet set1 set2
# Retrieve the combined set
SMEMBERS resultSet
This code takes two sets, merges their unique members into a new set, and stores it under a new key.
Look for repeated actions that take time.
- Primary operation: Scanning all members of each input set to combine them.
- How many times: Once for each member in each input set.
As the sets get bigger, the work grows roughly with the total number of unique members.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 to 20 operations |
| 100 | About 100 to 200 operations |
| 1000 | About 1000 to 2000 operations |
Pattern observation: The work grows roughly in direct proportion to the total number of elements in the input sets combined.
Time Complexity: O(n)
This means the time to combine sets grows linearly with the total number of elements in all input sets.
[X] Wrong: "SUNIONSTORE runs instantly no matter how big the sets are."
[OK] Correct: The command must look at every element in the input sets to combine them, so bigger sets take more time.
Understanding how set operations scale helps you reason about performance in real applications using Redis sets.
"What if we used SUNIONSTORE with three or more sets instead of two? How would the time complexity change?"