From 15b993f1ef6ec436c1c2f411232b27d150a6c168 Mon Sep 17 00:00:00 2001 From: Yanqi Lv Date: Fri, 8 Dec 2023 17:48:52 +0800 Subject: [PATCH] Optimize dictExpand of empty dict (#12847) If a dict is empty before `dictExpand`, we don't need to do rehashing actually. We can just create a new dict and set it as ht_table[0] to skip incremental rehashing and free the memory quickly. --- src/dict.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/dict.c b/src/dict.c index e88a843cc..541b2d066 100644 --- a/src/dict.c +++ b/src/dict.c @@ -273,6 +273,17 @@ int _dictExpand(dict *d, unsigned long size, int* malloc_failed) d->ht_table[1] = new_ht_table; d->rehashidx = 0; if (d->type->rehashingStarted) d->type->rehashingStarted(d); + /* If the dict is empty, we finish rehashing ASAP.*/ + if (d->ht_used[0] == 0) { + if (d->type->rehashingCompleted) d->type->rehashingCompleted(d); + zfree(d->ht_table[0]); + d->ht_size_exp[0] = new_ht_size_exp; + d->ht_used[0] = new_ht_used; + d->ht_table[0] = new_ht_table; + _dictReset(d, 1); + d->rehashidx = -1; + return DICT_OK; + } return DICT_OK; }