⚡️ Speed up function annotation_params_for_line by 123%
#84
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.
📄 123% (1.23x) speedup for
annotation_params_for_lineinplotly/shapeannotation.py⏱️ Runtime :
8.38 milliseconds→3.76 milliseconds(best of98runs)📝 Explanation and details
The optimized code achieves a 122% speedup through several key algorithmic improvements:
1. Eliminated expensive utility function calls
The original code repeatedly called
max(),min(),_mean(),_argmax(), and_argmin()on 2-element lists, which created unnecessary overhead. The optimization replaces these with direct comparisons since we always have exactly 2 points:max(Y),min(Y)→ directif y0 > y1:comparison_mean(Y)→ simple(y0 + y1) / 2.0arithmetic_argmax(Y),_argmin(Y)→ index assignment based on comparison result2. Optimized
_meanfunctionReplaced
sum(x)with a manual accumulation loop to avoid creating temporary iterators, reducing function call overhead for small lists.3. Reduced list indexing operations
Added local variable caching (
xi = x[i]) in_argmin/_argmaxto avoid repeated list lookups during comparisons.4. Fixed variable naming
Changed
positiontoposition_setin_prepare_positionto avoid shadowing and ensure consistent set comparisons throughout the function.Why this works:
Test case performance:
All test cases show consistent 70-130% speedups, with particularly strong gains on large-scale tests (1000+ iterations) where the reduced function call overhead compounds. The optimization is especially effective for typical use cases with standard coordinate ranges and common position strings.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-annotation_params_for_line-mhgdtzscand push.