HKEYS and HVALS in Redis - Time & Space Complexity
We want to understand how the time it takes to get all keys or all values from a Redis hash changes as the hash grows.
How does the number of fields in the hash affect the work Redis does when using HKEYS or HVALS?
Analyze the time complexity of the following code snippet.
HKEYS myhash
HVALS myhash
This code gets all the field names with HKEYS and all the field values with HVALS from the hash named 'myhash'.
- Primary operation: Redis scans through each field in the hash to collect keys or values.
- How many times: Once for each field in the hash.
As the number of fields in the hash grows, Redis must look at each field once to gather keys or values.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: The work grows directly with the number of fields; doubling fields doubles the work.
Time Complexity: O(n)
This means the time to get all keys or values grows in a straight line with the number of fields in the hash.
[X] Wrong: "HKEYS or HVALS always run in constant time, no matter how big the hash is."
[OK] Correct: Redis must look at every field to collect keys or values, so the time grows with the number of fields.
Knowing how commands like HKEYS and HVALS scale helps you understand performance when working with large hashes in Redis.
"What if we used HSCAN instead of HKEYS or HVALS? How would the time complexity change?"