⚡️ Speed up function _get_link_annotation by 35%
#228
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.
📄 35% (0.35x) speedup for
_get_link_annotationinlib/matplotlib/backends/backend_pdf.py⏱️ Runtime :
4.95 milliseconds→3.66 milliseconds(best of127runs)📝 Explanation and details
The optimization achieves a 35% speedup by eliminating redundant operations and reducing Python overhead in the
_get_coordinates_of_blockfunction.Key optimizations applied:
Single-pass min/max calculation: Replaced four separate generator expressions (
min(v[0] for v in vertices),max(v[0] for v in vertices), etc.) with one explicit loop that computes all bounds in a single pass over the vertices. This eliminates the overhead of creating four separate generators and iterating over the same data four times.Direct tuple flattening: Removed
itertools.chain.from_iterable(vertices)and replaced it with explicit coordinate access (vertices[0][0], vertices[0][1], ...). For the fixed case of 4 vertices (8 coordinates), this direct approach avoids iterator overhead and function call costs.Why this is faster:
itertools.chainfor this specific use caseImpact on workloads:
Based on the function references, this function is called from
draw_text,draw_mathtext, anddraw_texmethods whengc.get_url()is not None - meaning it's used for creating clickable links in PDF annotations. The optimization is particularly beneficial for:The test results show consistent 15-38% improvements across various scenarios, with the largest gains on simpler cases and bulk operations where the reduced overhead compounds significantly.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_get_link_annotation-miyjt1yvand push.