redis原始碼剖析 dict

2021-10-18 13:30:30 字數 1770 閱讀 6055

typedef struct dictentry  v;

struct dictentry *next;

} dictentry;

typedef struct dicttype 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 dictht;

typedef struct dict dict;

dictentry:每乙個資料元項

dicttype:多態函式 用於項的鍵值的複製、析構和鍵的比較函式

dictht:項的物件

table:項陣列

size:table陣列的大小

sizemask:size-1

used:資料元項數

dict:雜湊表資料結構

type:多態函式

provdata:多態函式的引數

ht[2]:dictht的陣列  ht[0]用於存放真正的資料元項  ht[1]主要用於rehash

rehashindex:rehash進度,rehash的時候並不是一次性完成,因為資料元項可能比較多 所以每次更新乙個hash項iterators:用於dictiterator

dictentry *dictaddraw(dict *d, void *key, dictentry **existing) 新增key/通過key獲取資料元

1.如果dict正在進行rehash 則更新乙個hash項

2.判斷key是否已經存在dict 存在則返回dictentry

3.如果正在進行rehash 選擇插入的是ht[1]雜湊表 因為插入ht[0]不能保證rehash的時候新插入的會轉移到ht[1]

4.更新ht的資訊

5.設定key  value(此時可以用上多態函式keydup  valuedup)

dictentry *dictgenericdelete(dict *d, const void *key, int nofree)  通過key刪除

1. 如果dict正在進行rehash 則更新乙個hash項

2.通過雜湊函式計算出hash值

3.從ht[0]開始 根據hash值找到對應的value 刪除它 通過nofress判斷是否需要釋放key value

4.如果ht[0]中找不到 並且當前正在進行rehash 則繼續從ht[1]中查詢

dictentry *dictgenericdelete(dict *d, const void *key, int nofree) 

d->ht[table].used--;

return he;

}prevhe = he;

he = he->next;

}if (!dictisrehashing(d)) break;

}return null; /* not found */

}

1.可以在o(1)時間複雜度內判斷key是否存在   並取到value

1.記憶體占用比較大

2.當hash函式很差時 可能導致查詢時間複雜度降為o(n)

Python原始碼剖析 Dict

為了刻畫某種關係,現代的程式語言都會提供關聯式的容器。關聯式容器中的元素分別是以 鍵 key 或值 value 這樣的形式存在。例如 3,5 3,6 就是一對對應的鍵與值。python中的關聯式容器是pydictobject。python通過pydictobject建立執行python位元組碼的執行...

redis原始碼之dict

大家都知道redis預設是16個db,但是這些db底層的設計結構是什麼樣的呢?我們來簡單的看一下原始碼,重要的字段都有所注釋 typedef struct redisdb redisdb redis中的所有kv都是存放在dict中的,dict型別在redis中非常重要。字典disc的資料結構如下 t...

redis原始碼剖析 skiplist

試想乙個業務場景 遊戲需要實現乙個實時更新的排行榜應該如何實現 首先想到使用有序的雙端鍊錶,因為插入的時間複雜度為o 1 但是定位的平均時間複雜度為o n 當頻繁更新排行榜的時候效率比較低 有沒有乙個結構 能夠滿足快速定位到相應的位置並插入?跳躍表就能滿足這個需求 跳躍表的思想是給資料結點建立索引 ...