⚡️ Speed up method ExceptionInfo._group_contains by 14%
#79
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.
📄 14% (0.14x) speedup for
ExceptionInfo._group_containsinsrc/_pytest/_code/code.py⏱️ Runtime :
1.52 milliseconds→1.33 milliseconds(best of114runs)📝 Explanation and details
The optimized code achieves a 14% speedup through targeted micro-optimizations in two hot path functions:
Key Optimizations:
_stringify_exceptionoptimization - This function showed significant improvement (34% faster based on profiler data):__notes__, so the optimization checksif not notes:and returns immediately, avoiding the expensivejoinoperationstr(exc)is computed once and stored inexc_strto avoid repeated string conversion_group_containsoptimization - Multiple micro-optimizations for this recursive function:isinstanceandBaseExceptionGroupare cached locally to avoid repeated global namespace lookups in the tight loopre.searchis cached whenmatchis present, reducing function lookups during iterationexc_group.exceptionsis cached asexcsto avoid repeated attribute accessPerformance Impact by Test Case:
_stringify_exceptionoptimizationsWhy These Optimizations Work:
The profiler shows
_stringify_exceptionand regex matching (re.search) consume 58% of total runtime in the original code. By optimizing the common path where exceptions lack notes and reducing global lookups in the recursive traversal, the code eliminates substantial overhead in exception handling workflows, particularly when processing large exception groups or performing pattern matching.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-ExceptionInfo._group_contains-mi9qvk3uand push.