⚡️ Speed up function axis_spanning_shape_annotation by 66%
#86
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.
📄 66% (0.66x) speedup for
axis_spanning_shape_annotationinplotly/shapeannotation.py⏱️ Runtime :
2.10 milliseconds→1.27 milliseconds(best of272runs)📝 Explanation and details
The optimized code achieves a 65% speedup through several key performance improvements:
Data Structure Optimizations:
X = [x0, x1]andY = [y0, y1]with tuplesX = (x0, x1)andY = (y0, y1)to eliminate unnecessary list object creation overhead{"top", "left"}instead ofset(["top", "left"])to avoid list creation and conversionEliminated Function Call Overhead:
_mean(),_argmax(), and_argmin()function calls with inline calculations:_mean([y0, y1])→(y0 + y1) / 2.0(eliminates list creation + function call)_argmax(Y)→0 if y0 > y1 else 1(eliminates iteration overhead)max(Y)andmin(Y)→ direct comparisons likey0 if y0 > y1 else y1Precomputed Common Values:
annotation_params_for_rect(), computedminx,maxx,miny,maxy,meanx,meanyonce and reused them across multiple conditions, avoiding redundantmin([x0, x1])andmax([x0, x1])callsOptimized Dictionary Iteration:
for k, v in shape_dict.items()instead offor k in shape_dict.keys()followed byshape_dict[k]lookup to eliminate repeated key lookupsStreamlined Filtering Logic:
list(filter(lambda k: k.startswith(prefix), kwargs.keys()))with a single-pass loop that both filters keys and extracts the annotation position value, reducing iterations and lambda overheadThe optimizations are particularly effective for test cases with complex position calculations (like line positioning with "top right", "bottom left") where the function call elimination provides the biggest gains. Simple cases like returning None early also benefit significantly from the streamlined filtering logic.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-axis_spanning_shape_annotation-mhgecengand push.