0
0
Redisquery~5 mins

HKEYS and HVALS in Redis - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: HKEYS and HVALS
O(n)
Understanding Time 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?

Scenario Under Consideration

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'.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

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
10About 10 operations
100About 100 operations
1000About 1000 operations

Pattern observation: The work grows directly with the number of fields; doubling fields doubles the work.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Knowing how commands like HKEYS and HVALS scale helps you understand performance when working with large hashes in Redis.

Self-Check

"What if we used HSCAN instead of HKEYS or HVALS? How would the time complexity change?"