redis内存优化————有着很多个域hash保存对象可以比建立很多个键值对更加节约内存

redis文档中提到,采用有着很多个域hash保存对象可以比建立很多个键值对更加节约内存,但存在一个缺陷是只有key才具有存活期,hash不能对域设置存活期。

具体原理是因为redis在hash的项数少于一定数目时(这个数目可以由用户自己设置字段如下),会采用更加节约内存的数据结构,但是这种数据结构会带来O(N)的时间复杂度,而不是hashtable的O(1)常数时间复杂度,但是由于N很小,在均摊时间上可以视为常数时间,并且zipmap有更好的局部性,能够提高cache的命中率,提升内存访问速度,借此来抵消时间上的花费。

hash-max-zipmap-entries 256(元素小于256使用zipmap存储)

具体做法如下:(懒得打了,反正是自己看)

Now let's assume the objects we want to cache are numbered, like:

  • object:102393
  • object:1234
  • object:5

This is what we can do. Every time there is to perform a SET operation to set a new value, we actually split the key into two parts, one used as a key, and used as field name for the hash. For instance the object named "object:1234" is actually split into:

  • a Key named object:12
  • a Field named 34

So we use all the characters but the latest two for the key, and the final two characters for the hash field name. To set our key we use the following command:

HSET object:12 34 somevalue

As you can see every hash will end containing 100 fields, that is an optimal compromise between CPU and memory saved.

上面这句话可能就是工程经验吧,记住就好了哼!


之后我很好奇zipmap到底是一个什么样的数据结构,有这么高的内存效率,英文文档说内存效率是10倍(评价内存效率是5倍),而且记录跟存储的区别是什么。下篇博客看看

你可能感兴趣的:(redis文档笔记)