⚡️ Speed up function _is_floats_color by 59%
#397
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.
📄 59% (0.59x) speedup for
_is_floats_colorinpandas/plotting/_matplotlib/style.py⏱️ Runtime :
275 microseconds→173 microseconds(best of158runs)📝 Explanation and details
The optimized version replaces a chained boolean expression with early-return conditional statements, providing a 58% speedup from 275μs to 173μs.
Key Optimization: Early Exit Pattern
The original code used a single
return bool(...)statement withandoperators that forced evaluation of all conditions even when earlier ones failed. The optimized version uses separateifstatements with early returns, allowing the function to exit immediately when any condition fails.Specific Performance Improvements:
is_list_like(color)returnsFalse, the optimized version exits immediately instead of continuing to evaluate length and type checksbool()wrapper: The original wrapped the entire expression inbool(), adding unnecessary overheadall()generator with explicit loop: Theall(isinstance(x, (int, float)) for x in color)creates a generator and callsall(), while the explicitforloop with early return is more efficientPerformance Characteristics by Test Case:
Impact on Workloads:
The function is called by
_is_single_color()in matplotlib plotting style detection. Since this is likely in the rendering pipeline, the 58% speedup will meaningfully improve plot generation performance, especially when processing many color specifications or when invalid colors are frequently encountered (which trigger the fastest exit paths).✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_is_floats_color-mir27r1iand push.