看到一个问题, Redis strings vs Redis hashes to represent JSON: efficiency? 内容如下:
I want to store a JSON payload into redis. There's really 2 ways I can do this:
- One using a simple string keys and values.
- key:user, value:payload (the entire JSON blob which can be 100-200 KB)
- SET user:1 payload
- Using hashes
- HSET user:1 username "someone"
- HSET user:1 location "NY"
- HSET user:1 bio "STRING WITH OVER 100 lines"
Keep in mind that if I use a hash, the value length isn't predictable. They're not all short such as the bio example above.
Which is more memory efficient? Using string keys and values, or using a hash?
string 和 hash 直观测试
首先我们先测试用数据测试一下,测试数据结构如下:
values = {
"name": "gs",
"age": 1
}
使用for 生成10w个key,key的生成规则为:
for i in range(100000):
key = "object:%d" % i
把数据分别以hash

本文探讨了在Redis中存储JSON数据时,使用string和hash的内存效率问题。通过测试发现,小型hash会被编码为ziplist,节省空间。当数据量增大,hash转为hashtable,仍能保持较好的读写速度。选择存储方式应根据数据结构和使用场景,结构化数据且常用部分字段时,hash更优;大量不同数据或需完整读取时,string更合适。
最低0.47元/天 解锁文章
777





