⚡️ Speed up function __getattr__
by 8%
#12
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.
📄 8% (0.08x) speedup for
__getattr__
inquantecon/lqnash.py
⏱️ Runtime :
23.5 microseconds
→21.7 microseconds
(best of130
runs)📝 Explanation and details
The optimization achieves a 7% speedup by eliminating unnecessary dynamic lookups in a deprecation wrapper module.
Key optimizations:
Direct string comparison: Changed
if name not in __all__:
toif name != 'nnash':
. Since__all__
contains only one element ('nnash'
), a direct string comparison is faster than checking membership in a list, avoiding the overhead of iterating through the container.Direct attribute access: Replaced
return getattr(_lqnash, name)
withreturn _lqnash.nnash
. Since we already validated thatname == 'nnash'
, we can directly access the known attribute instead of using the slowergetattr()
function which performs dynamic attribute resolution.Explicit
__all__
definition: Added__all__ = ['nnash']
at module level to make the allowed attributes explicit and ensure consistent behavior.Why this works: The original code used generic dynamic lookups suitable for multiple attributes, but since this deprecated module only exposes one attribute (
nnash
), we can use faster direct operations. String equality is faster than list membership, and direct attribute access bypasses Python's attribute resolution machinery.Test case performance: The optimization shows consistent improvements across all test scenarios, with particularly strong gains for invalid attribute cases (10-21% faster) where the direct comparison quickly rejects invalid names without container iteration overhead.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-__getattr__-mggq7ikl
and push.