Redis 字典

来源:互联网 发布:淘宝店铺装修特效 编辑:程序博客网 时间:2024/06/11 09:09

Redis Dict

字典,哈希表,HashMap仅仅是说法不同而已。本质上就是一种key,value存储,可以高效的存储和访问。

定义

redis dict

typedef struct dictEntry {    void *key;    void *val;    struct dictEntry *next;} dictEntry;typedef struct dictType {    unsigned int (*hashFunction)(const void *key);    void *(*keyDup)(void *privdata, const void *key);    void *(*valDup)(void *privdata, const void *obj);    int (*keyCompare)(void *privdata, const void *key1, const void *key2);    void (*keyDestructor)(void *privdata, void *key);    void (*valDestructor)(void *privdata, void *obj);} dictType;/* This is our hash table structure. Every dictionary has two of this as we * implement incremental rehashing, for the old to the new table. */typedef struct dictht {    dictEntry **table;    unsigned long size;    unsigned long sizemask;    unsigned long used;} dictht;typedef struct dict {    dictType *type;    void *privdata;    dictht ht[2];    int rehashidx; /* rehashing not in progress if rehashidx == -1 */    int iterators; /* number of iterators currently running */} dict;

总结

  1. 该哈希表使用拉链法,对于冲突的元素,用单链表链接起来。
  2. 当哈希表冲突严重,需要rehash的时候,需要扩大哈希表容量,使用h[1]来分配较大的空间,再把h[0]中的entry重新rehash到h[1]中去。如果h[0]元素很多,重新rehash一遍所有元素是需要花很多时间的,因此采用的思路是内部维护一个rehashidx变量,在每次访问哈希表的时候,仅对其中的一个索引链进行搬移操作。相当于把整个哈希表的rehash平均到每次的访问中,把需要较多的时间分散开来。当rehash完成后,把h[0]释放掉,h[1]赋值给h[0]即可。
  3. 在rehash的过程中,相当于h[0]和h[1]同时有数据,因此需要访问h[0]和h[1]。
  4. dictType中维护一组函数指针,用于对节点中Key和Value的通用操作。