0
0
Redisquery~5 mins

Memory-efficient data structures in Redis

Choose your learning style9 modes available
Introduction
Memory-efficient data structures help store data in Redis using less memory, making your database faster and cheaper to run.
When you have lots of small pieces of data to store, like user sessions or counters.
When you want to save memory on a server with limited resources.
When you need to handle many keys without slowing down Redis.
When you want to reduce the cost of cloud storage by using less memory.
When you want your Redis database to respond faster by using compact data formats.
Syntax
Redis
Use Redis commands that create or work with memory-efficient structures like hashes, sets, sorted sets, or bitmaps.

Example:
HSET myhash field1 value1
SADD myset member1
SETBIT mybitmap 10 1
Redis automatically uses memory-efficient encodings for small hashes and sets.
You can check the encoding of a key with the command: OBJECT ENCODING keyname
Examples
Stores user data in a hash, which is memory-efficient for small sets of fields.
Redis
HSET user:1000 name "Alice" age 30
Stores a set of online users efficiently.
Redis
SADD online_users user1 user2 user3
Uses a bitmap to store flags in a very compact way.
Redis
SETBIT user_flags 5 1
Sample Program
This example creates a small hash for user:1 and then checks its memory encoding.
Redis
HSET user:1 name "Bob" age 25
HSET user:1 city "Paris"
OBJECT ENCODING user:1
OutputSuccess
Important Notes
Small hashes and sets are stored as ziplists or intsets internally, which use less memory.
Avoid storing large values in hashes if you want to keep memory usage low.
Use bitmaps for boolean flags to save space compared to strings or hashes.
Summary
Memory-efficient data structures help save RAM and improve Redis speed.
Hashes, sets, and bitmaps are common memory-saving structures in Redis.
Redis automatically optimizes small data sets to use less memory.