⚡️ Speed up function _calculate_quad_point_coordinates by 15%
#226
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.
📄 15% (0.15x) speedup for
_calculate_quad_point_coordinatesinlib/matplotlib/backends/backend_pdf.py⏱️ Runtime :
2.74 milliseconds→2.38 milliseconds(best of67runs)📝 Explanation and details
The optimization achieves a 15% speedup through two key improvements:
1. Zero-angle fast path: When
angle=0(no rotation), the code bypasses expensive trigonometric calculations by directly settingsin_angle=0.0andcos_angle=1.0. This eliminates calls tomath.radians(),math.sin(), andmath.cos()for the common case of non-rotated rectangles.2. Computation reuse: Pre-computes
height_sin,height_cos,width_cos, andwidth_sinonce, eliminating repeated multiplications in the coordinate calculations.Performance impact by use case:
Context relevance: The function is called from
_get_coordinates_of_block()in PDF backend rendering, suggesting it's in a hot path for PDF generation. Since many PDF elements (text, images, shapes) are typically unrotated, the zero-angle fast path should provide significant real-world benefits for matplotlib's PDF output performance.The optimization preserves exact mathematical behavior while trading a small conditional overhead for substantial gains in the common unrotated case.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_calculate_quad_point_coordinates-miyj2c38and push.