⚡️ Speed up function _get_span_op
by 128%
#49
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.
📄 128% (1.28x) speedup for
_get_span_op
insentry_sdk/tracing_utils.py
⏱️ Runtime :
8.39 milliseconds
→3.67 milliseconds
(best of38
runs)📝 Explanation and details
The optimization moves the dictionary mapping from inside the function to module-level as a constant
_MAPPING
. This eliminates the overhead of recreating the dictionary on every function call.Key changes:
_MAPPING
Why this is faster:
In Python, dictionary creation involves memory allocation and key-value pair insertion operations that occur every time the function is called. By moving the mapping to module level, it's created only once when the module is imported, then reused for all subsequent function calls. This removes the dictionary creation overhead entirely from the hot path.
Performance characteristics:
The optimization shows consistent 90-173% speedup across all test cases, with particularly strong gains for:
This is a classic Python optimization pattern where moving expensive object creation out of frequently-called functions to module initialization provides substantial performance benefits.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_get_span_op-mg9nsltp
and push.