INCR and DECR for counters in Redis - Time & Space Complexity
When using Redis commands like INCR and DECR, it's important to know how the time to run these commands changes as we use them more.
We want to understand how the cost grows when we increase or decrease counters many times.
Analyze the time complexity of the following Redis commands.
INCR counter
DECR counter
INCR counter
DECR counter
This code increases and decreases a counter value stored in Redis multiple times.
Look for repeated actions that take time.
- Primary operation: Each INCR or DECR command updates the counter once.
- How many times: Each command runs once per call, so if you run n commands, you have n operations.
Each command takes about the same time no matter the counter's value.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The total time grows directly with the number of commands run.
Time Complexity: O(1)
This means each INCR or DECR command takes the same small amount of time, no matter how big the counter is.
[X] Wrong: "INCR or DECR commands take longer as the counter value gets bigger."
[OK] Correct: Redis stores numbers efficiently, so changing a number is always quick and does not depend on its size.
Knowing that simple counter updates are fast helps you explain how Redis handles many quick changes efficiently, a useful skill in real projects.
"What if we used INCRBY to add a large number instead of 1? How would the time complexity change?"