Skip to content

gh-141510: Optimize hash(frozendict)#144919

Merged
vstinner merged 2 commits intopython:mainfrom
vstinner:frozendict_hash
Feb 17, 2026
Merged

gh-141510: Optimize hash(frozendict)#144919
vstinner merged 2 commits intopython:mainfrom
vstinner:frozendict_hash

Conversation

@vstinner
Copy link
Member

@vstinner vstinner commented Feb 17, 2026

hash(frozendict) no longer creates a temporary items view and a temporary frozenset object.

Copy frozenset_hash() code to frozendict_hash().

hash(frozendict) no longer creates a temporary items view and a
temporary frozenset object.

Copy frozenset_hash() code to frozendict_hash().
Py_hash_t hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->ma_hash);
if (hash != -1) {
return hash;
Py_hash_t shash = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->ma_hash);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why atomic operation is needed?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PyFrozenDictObject.ma_hash is mutable and so it needs a lock to handle properly concurrent access.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the same for the Unicode strings hash: the string is immutable, but the hash member is mutable. So unicode_hash() uses atomic operations to get and set the hash member.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah got it

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, the hash is "lazily" computed so we need to use relaxed atomics here.

Copy link
Member

@corona10 corona10 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm!

@vstinner vstinner merged commit 8e211b1 into python:main Feb 17, 2026
45 checks passed
@vstinner vstinner deleted the frozendict_hash branch February 17, 2026 17:39
@vstinner
Copy link
Member Author

Merged, thanks for reviews!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

Comments