⚡️ Speed up function should_propagate_trace
by 245%
#45
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.
📄 245% (2.45x) speedup for
should_propagate_trace
insentry_sdk/tracing_utils.py
⏱️ Runtime :
202 milliseconds
→58.5 milliseconds
(best of28
runs)📝 Explanation and details
The optimization introduces regex compilation caching to
match_regex_list
, which provides dramatic performance improvements when the same regex patterns are matched repeatedly.Key Changes:
re.search()
with raw strings (which internally compiles patterns each time), the code now pre-compiles all patterns usingre.compile()
and caches them based on theregex_list
identity andsubstring_matching
flag.anchors is moved to the caching phase, avoiding repeated string operations during matching.
Why This Speeds Up:
) happens only during cache creation, not on every match attempt.
Performance Benefits by Test Case:
test_large_many_trace_targets_one_match
: 27.3ms → 3.77μs)test_edge_targets_with_special_regex
show 2,295% speedupThe optimization is particularly effective for Sentry's trace propagation use case, where the same
trace_propagation_targets
list is likely checked against many different URLs throughout an application's lifetime.✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
tracing/test_misc.py::test_should_propagate_trace
tracing/test_misc.py::test_should_propagate_trace_to_sentry
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-should_propagate_trace-mg9mvvsh
and push.