gpt4 book ai didi

Redis 哈希与字符串内存成本

转载 作者:可可西里 更新时间:2023-11-01 11:22:13 27 4
gpt4 key购买 nike

我做了一些实验,似乎 Redis 哈希几乎总是比字符串更节省空间,即使哈希包含单个字段也是如此!

import redis
rc = redis.Redis(host='127.0.0.1',port=1234)

rc.flushdb()
pipe = rc.pipeline()
for i in range(1000000):
pipe.set('stream:'+str(i)+':target',True)
f = pipe.execute()
# uses 236 MB

rc.flushdb()
pipe = rc.pipeline()
for i in range(1000000):
pipe.hset('stream:'+str(i),'target',True)
f = pipe.execute()
# uses 170 MB

rc.flushdb()
pipe = rc.pipeline()
for i in range(500000):
pipe.set('stream:'+str(i)+':target',True)
pipe.set('stream:'+str(i)+':ws',True)
f = pipe.execute()
# uses 238 MB

rc.flushdb()
pipe = rc.pipeline()
for i in range(500000):
pipe.hset('stream:'+str(i),':target',True)
pipe.hset('stream:'+str(i),':ws',True)
f = pipe.execute()
# uses 113 MB

哈希和字符串都具有 O(1) 的平摊写入/读取成本。如果我不需要使用最花哨的操作,如 APPEND、GETBIT、SETBIT、RANGE 等,而只使用纯粹的 SET/GET 语义,那么散列不是总是更可取吗?我想念什么疯狂的东西吗?另外,我很想知道为什么哈希的空间效率要高得多。

最佳答案

Memory Optimization文章讨论了您提出的一些问题。

如果您可以这样表示数据,redis 的建议是使用哈希。 “小散列被编码在一个非常小的空间中,所以你应该尽可能地尝试使用散列来表示你的数据”。

如果 Redis 可以将散列打包到一个数组中,并且仍然以 O(1) 的速度进行查询,那么 Redis 认为散列很小。将数据放在连续的内存区域中也有助于提高性能,特别是如果数组的相邻元素是在您的盒子上的缓存行的框架内读取的。

在redis config中你可以找到以下设置,

# Hashes are encoded using a memory efficient data structure when they have a
# small number of entries, and the biggest entry does not exceed a given
# threshold. These thresholds can be configured using the following directives.
hash-max-ziplist-entries 512
hash-max-ziplist-value 64

您需要在上述阈值的两侧重复测试。总的来说,最好让您的测试尽可能地模仿您的真实数据和访问模式。您的问题的前提是应始终使用哈希,但请记住,您指望优化启发式算法对您作为用户而言并不完全透明。

关于Redis 哈希与字符串内存成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20811335/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com