⚡️ Speed up function has_level_label by 76%
#94
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.
📄 76% (0.76x) speedup for
has_level_labelinpandas/plotting/_matplotlib/converter.py⏱️ Runtime :
114 microseconds→64.5 microseconds(best of220runs)📝 Explanation and details
The optimized code achieves a 76% speedup through three key optimizations:
1. Eliminated redundant size calculations: The original code called
label_flags.sizetwice in the complex conditional. The optimized version stores it once in a local variable, reducing NumPy attribute access overhead.2. Restructured branching logic: Instead of a complex compound conditional with short-circuit evaluation, the optimized version uses sequential
ifstatements that handle edge cases first (empty arrays, single-element arrays), then falls through to the common case. This reduces the total number of condition evaluations for most inputs.3. Used
.item()for single-element access: When dealing with single-element arrays,.item()is faster than indexing ([0]) because it directly extracts the scalar value without array indexing overhead or potential memory copying.The optimization is particularly effective for the most common test cases:
.item()The performance gains are consistent across different array sizes and data types, with the largest improvements seen in single-element array scenarios where the original code's redundant operations had the most impact.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-has_level_label-mhbpk08sand push.