⚡️ Speed up method FormattedExcinfo.get_source by 10%
#80
+50
−29
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.
📄 10% (0.10x) speedup for
FormattedExcinfo.get_sourceinsrc/_pytest/_code/code.py⏱️ Runtime :
325 microseconds→296 microseconds(best of69runs)📝 Explanation and details
The optimized code achieves a 10% speedup by reducing redundant computations and replacing inefficient for-loops with faster list comprehensions and conditional checks.
Key optimizations applied:
Avoided repeated
len()calls: The original code calledlen(source)andlen(source.lines)multiple times. The optimized version caches these values assource_lenand reusessource.linesassource_lines, eliminating redundant attribute lookups and length calculations.Replaced for-loops with list comprehensions: The original code used explicit for-loops to append lines with prefixes:
The optimized version uses list comprehensions with
extend():This is faster because list comprehensions are optimized at the C level in Python.
Added conditional checks to avoid unnecessary iterations: The optimized code adds
if line_index > 0:andif line_index + 1 < source_len:checks to skip empty slice iterations, avoiding the overhead of creating and iterating over empty lists.Performance impact by test case:
The optimizations are particularly effective for larger source files where the reduced loop overhead and cached values provide substantial benefits, while maintaining identical functionality for all input scenarios.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-FormattedExcinfo.get_source-mi9r5fomand push.