HSET and HGET for fields in Redis - Time & Space Complexity
When working with Redis hashes, it is important to understand how fast commands like HSET and HGET run as the data grows.
We want to know how the time to set or get a field changes when the number of fields in the hash increases.
Analyze the time complexity of the following Redis commands.
HSET user:1000 name "Alice"
HSET user:1000 age "30"
HGET user:1000 name
HGET user:1000 age
This code sets two fields in a hash and then retrieves them.
Look for repeated actions that affect time.
- Primary operation: Accessing a field inside a hash (setting or getting).
- How many times: Each command accesses one field directly without scanning all fields.
Getting or setting a field takes about the same time no matter how many fields are in the hash.
| Input Size (number of fields) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays roughly the same even as the number of fields grows.
Time Complexity: O(1)
This means setting or getting a field in a Redis hash takes constant time, no matter how many fields are stored.
[X] Wrong: "Accessing a field in a hash gets slower as the hash grows because Redis must look through all fields."
[OK] Correct: Redis uses a data structure that lets it find fields directly without scanning, so time stays constant.
Knowing that Redis hash field access is constant time helps you explain how Redis handles data efficiently, a useful skill in many real-world projects.
"What if we used HGETALL to get all fields instead of HGET for one field? How would the time complexity change?"