Skip to content

Commit 42bae3a

Browse files
authored
bpo-40602: Optimize _Py_hashtable_get_ptr() (GH-20066)
_Py_hashtable_get_entry_ptr() avoids comparing the entry hash: compare directly keys. Move _Py_hashtable_get_entry_ptr() just after _Py_hashtable_get_entry_generic().
1 parent 5b0a303 commit 42bae3a

File tree

1 file changed

+23
-24
lines changed

1 file changed

+23
-24
lines changed

Python/hashtable.c

+23-24
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,29 @@ _Py_hashtable_get_entry_generic(_Py_hashtable_t *ht, const void *key)
193193
}
194194

195195

196+
// Specialized for:
197+
// hash_func == _Py_hashtable_hash_ptr
198+
// compare_func == _Py_hashtable_compare_direct
199+
static _Py_hashtable_entry_t *
200+
_Py_hashtable_get_entry_ptr(_Py_hashtable_t *ht, const void *key)
201+
{
202+
Py_uhash_t key_hash = _Py_hashtable_hash_ptr(key);
203+
size_t index = key_hash & (ht->num_buckets - 1);
204+
_Py_hashtable_entry_t *entry = entry = TABLE_HEAD(ht, index);
205+
while (1) {
206+
if (entry == NULL) {
207+
return NULL;
208+
}
209+
// Compare directly keys (ignore entry->key_hash)
210+
if (entry->key == key) {
211+
break;
212+
}
213+
entry = ENTRY_NEXT(entry);
214+
}
215+
return entry;
216+
}
217+
218+
196219
void*
197220
_Py_hashtable_steal(_Py_hashtable_t *ht, const void *key)
198221
{
@@ -275,30 +298,6 @@ _Py_hashtable_get(_Py_hashtable_t *ht, const void *key)
275298
}
276299

277300

278-
// Specialized for:
279-
// hash_func == _Py_hashtable_hash_ptr
280-
// compare_func == _Py_hashtable_compare_direct
281-
_Py_hashtable_entry_t *
282-
_Py_hashtable_get_entry_ptr(_Py_hashtable_t *ht, const void *key)
283-
{
284-
Py_uhash_t key_hash = _Py_hashtable_hash_ptr(key);
285-
size_t index = key_hash & (ht->num_buckets - 1);
286-
_Py_hashtable_entry_t *entry = entry = TABLE_HEAD(ht, index);
287-
while (1) {
288-
if (entry == NULL) {
289-
return NULL;
290-
}
291-
if (entry->key_hash == key_hash) {
292-
if (entry->key == key) {
293-
break;
294-
}
295-
}
296-
entry = ENTRY_NEXT(entry);
297-
}
298-
return entry;
299-
}
300-
301-
302301
int
303302
_Py_hashtable_foreach(_Py_hashtable_t *ht,
304303
_Py_hashtable_foreach_func func,

0 commit comments

Comments
 (0)