⚡️ Speed up function _get_frame_module_abs_path
by 50%
#42
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.
📄 50% (0.50x) speedup for
_get_frame_module_abs_path
insentry_sdk/tracing_utils.py
⏱️ Runtime :
23.4 microseconds
→15.6 microseconds
(best of116
runs)📝 Explanation and details
The optimization replaces a try-except block with defensive attribute access using
getattr()
, which provides significant performance improvements.Key Changes:
try: return frame.f_code.co_filename except Exception: return None
withgetattr()
callsgetattr(frame, "f_code", None)
to safely access thef_code
attributegetattr(code, "co_filename", None)
to safely access theco_filename
attributeWhy This Is Faster:
Exception handling overhead eliminated: The original code relies on Python's exception handling mechanism, which has significant overhead even when no exception occurs. The optimized version uses
getattr()
with default values, avoiding exception creation entirely.Reduced attribute access: The optimized version performs controlled attribute lookups with fallbacks, which is more efficient than the try-catch pattern for handling missing attributes.
Early termination: The conditional check
if code is not None
allows early return without additional attribute access whenf_code
is missing.Test Case Performance:
The optimization shows substantial gains across all error cases:
f_code
: 119-135% fasterco_filename
: 95-114% fasterThe few cases showing minor slowdowns (5-17%) are when attributes exist and contain valid data, where the getattr overhead slightly exceeds direct access. However, the overall 50% speedup demonstrates this optimization excels in error-prone scenarios while maintaining acceptable performance in success cases.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_get_frame_module_abs_path-mg9lmk1t
and push.