speed-up Structure instantiation #4415
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR speeds up the instantiation of
Structure
objects by preventing hash collisions in thelru_cache
ofget_el_sp
and increasing itsmaxsize
. The issue is that currentlyElement
objects are hashed to the same value as the integer atomic numbers (e.g.,Element[H]
maps to the same hash asint(1)
). This forces thelru_hash
to perform an expensive__eq__
comparison between the two, which reduces the performance of instantiating manyStructure
objects. Also here we increase themaxsize
ofget_el_sp
'slru_cache
to 1024 for further performance improvements.This reduces time taken to instantiate 100,000
Structure
objects from 31 seconds to 8.7s (avoid hash collisions) to 6.1s (also increasemaxsize
to 1024). Test snippet:Unless I'm missing some deep reason for why the hash of
Element
objects should be the same as their atomic number hashes, this should not lead to any different behavior of the code.Major changes:
ElementBase
__hash__
function to map to a different value than the atomic numbermaxsize
ofget_el_sp
'slru_cache
to 1024Checklist
ruff
.mypy
.duecredit
@due.dcite
decorators to reference relevant papers by DOI (example)Tip: Install
pre-commit
hooks to auto-check types and linting before every commit: