Skip to content

Commit abf7030

Browse files
authored
Shrink dict without rehashing (redis#11540)
When we're shrinking the hash table, we don't need to hash the keys. Since the table sizes are powers of two, we can simply mask the bucket index in the larger table to get the bucket index in the smaller table. We avoid loading the keys into memory and save CPU time.
1 parent ce4ebe6 commit abf7030

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

src/dict.c

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,14 @@ int dictRehash(dict *d, int n) {
229229

230230
nextde = de->next;
231231
/* Get the index in the new hash table */
232-
h = dictHashKey(d, de->key) & DICTHT_SIZE_MASK(d->ht_size_exp[1]);
232+
if (d->ht_size_exp[1] > d->ht_size_exp[0]) {
233+
h = dictHashKey(d, de->key) & DICTHT_SIZE_MASK(d->ht_size_exp[1]);
234+
} else {
235+
/* We're shrinking the table. The tables sizes are powers of
236+
* two, so we simply mask the bucket index in the larger table
237+
* to get the bucket index in the smaller table. */
238+
h = d->rehashidx & DICTHT_SIZE_MASK(d->ht_size_exp[1]);
239+
}
233240
de->next = d->ht_table[1][h];
234241
d->ht_table[1][h] = de;
235242
d->ht_used[0]--;

0 commit comments

Comments
 (0)