⚡️ Speed up function __getattr__ by 8%
#47
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/kalman.py⏱️ Runtime :
1.50 milliseconds→1.40 milliseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 7% speedup by making two key micro-optimizations to the
__getattr__function:1. Direct comparison vs. membership check:
if name not in __all__performs a linear search through the__all__listif name != 'Kalman'does a direct string comparison__all__contains only one element ('Kalman'), the direct comparison eliminates the overhead of Python'sinoperator and list iteration2. Static warning message:
f"Please use{name}from..."which requires string formatting on every callnameis always'Kalman'in the valid code pathPerformance impact by test case:
The optimizations show consistent improvements across all test scenarios:
Why this matters:
This is a deprecation module that gets called whenever legacy code accesses
quantecon.kalman.Kalman. While each individual call saves only microseconds, the cumulative effect can be meaningful in codebases with frequent legacy imports. The optimizations are particularly effective because they target the most common operations (string comparison and warning generation) in a function that's likely called repeatedly during module imports and attribute access.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-__getattr__-mj9w9sztand push.