Hash vs string for objects in Redis - Performance Comparison
When storing objects in Redis, we can use either strings or hashes. Understanding how the time to access or update data changes with size helps us choose the best option.
We want to know how the time to get or set fields grows as the object gets bigger.
Analyze the time complexity of these Redis commands for storing and accessing objects.
# Using string to store whole object
SET user:1000 "{\"name\":\"Alice\", \"age\":30, \"city\":\"NY\"}"
GET user:1000
# Using hash to store fields separately
HSET user:1000 name "Alice" age 30 city "NY"
HGET user:1000 name
HGETALL user:1000
This code shows storing an object as one string versus storing fields in a hash and accessing them.
Look at what repeats when accessing or updating data.
- Primary operation: Accessing fields inside the stored object.
- How many times: For strings, the whole object is read or written at once. For hashes, each field is accessed individually.
Think about how time changes as the object grows with more fields.
| Input Size (fields) | Approx. Operations |
|---|---|
| 10 | String: reads/writes whole object (small size), Hash: reads/writes individual fields (10 ops for all fields) |
| 100 | String: reads/writes whole bigger object, Hash: 100 ops for all fields, 1 op for single field |
| 1000 | String: reads/writes very large object, Hash: 1000 ops for all fields, 1 op for single field |
Pattern observation: String operations take longer as the whole object grows. Hash single field access stays fast regardless of object size.
Time Complexity: O(n) for string whole-object access, O(1) for hash single field access
This means reading or writing the whole string grows with object size, but accessing one field in a hash stays quick no matter how big the object is.
[X] Wrong: "Accessing a field in a hash takes as long as reading the whole object stored as a string."
[OK] Correct: Hashes let Redis jump directly to the field, so single field access is fast and does not depend on total object size.
Knowing how Redis handles strings and hashes helps you pick the right data structure for fast access. This skill shows you understand practical trade-offs in real projects.
"What if we used HGETALL to get all fields from a hash instead of HGET for one field? How would the time complexity change?"