⚡️ Speed up function safe_getattr by 57%
#466
Open
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.
📄 57% (0.57x) speedup for
safe_getattrinmarimo/_runtime/reload/autoreload.py⏱️ Runtime :
2.51 milliseconds→1.61 milliseconds(best of62runs)📝 Explanation and details
The optimization replaces a try/except approach with a hasattr check, delivering a 56% speedup by eliminating exception handling overhead in the common case where attributes exist.
Key changes:
ModuleNotFoundError, the code first checks if the attribute exists usinghasattr(obj, attr)getattr(obj, attr)without a default parameter, avoiding the overhead of exception handling machineryWhy this optimization works:
Exception handling in Python has significant overhead even when no exception is raised. The original code spent 19.3% of time on the try statement setup and 70.2% on the getattr call within the try block. The optimized version eliminates this overhead by using
hasattr()to pre-check attribute existence - a much faster operation that doesn't involve exception handling machinery.Performance characteristics by test case:
hasattrcall, but this is minimalThis optimization is particularly effective for codebases where
safe_getattris frequently called on objects that may or may not have the requested attribute, as it converts the expensive exception path into a fast boolean check.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-safe_getattr-mhaz7h2eand push.