SET and GET commands in Redis - Time & Space Complexity
When using Redis commands like SET and GET, it's helpful to know how the time to run these commands changes as data grows.
We want to understand how fast these commands work when storing or retrieving data.
Analyze the time complexity of the following code snippet.
SET user:1000 "Alice"
GET user:1000
SET user:1001 "Bob"
GET user:1001
SET user:1002 "Carol"
GET user:1002
This code stores and retrieves simple string values by key in Redis.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Each SET or GET command accesses a key in the database.
- How many times: Each command runs once per key, no loops or recursion involved.
Each command works directly with one key, so the time to run one command stays about the same no matter how many keys exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 operation per command |
| 100 | About 1 operation per command |
| 1000 | About 1 operation per command |
Pattern observation: The time to run each command stays steady even as the number of keys grows.
Time Complexity: O(1)
This means each SET or GET command takes about the same time regardless of how many keys are stored.
[X] Wrong: "The GET command takes longer if there are more keys stored in Redis."
[OK] Correct: Redis uses a fast way to find keys, so GET runs in constant time no matter how many keys exist.
Knowing that SET and GET run quickly helps you explain how Redis can handle many requests fast, a useful skill in real projects and interviews.
"What if we changed the keys to very long strings? How would the time complexity change?"