⚡️ Speed up function _is_single_color by 30%
#396
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.
📄 30% (0.30x) speedup for
_is_single_colorinpandas/plotting/_matplotlib/style.py⏱️ Runtime :
517 microseconds→397 microseconds(best of140runs)📝 Explanation and details
The optimized code achieves a 30% speedup through two key optimizations:
1. ColorConverter instance caching: The original code created a new
matplotlib.colors.ColorConverter()instance on every call to_is_single_string_color. The optimized version caches this instance as a module-level variable_conv. This eliminates repeated object instantiation overhead, which the profiler shows reduced time from 43,939ns to 15,090ns per call in_is_single_string_color.2. More efficient validation in
_is_floats_color: The original version used a chained boolean expression withall()which creates a generator and evaluates all elements even when early failures occur. The optimized version restructures the logic with early returns:is_list_like(color)first and returnsFalseimmediately for non-sequencesn != 3 and n != 4) before any iterationforloop with early return instead ofall(), avoiding generator overheadThe profiler shows this reduced
_is_floats_colorexecution time from 522,257ns to 358,781ns total.Impact on workloads: The function references show
_is_single_coloris called from_get_colors_from_colorand_gen_list_of_colors_from_iterable, indicating it's in a hot path for color processing in matplotlib plotting. The test results show particularly strong improvements (50-70% faster) for RGB/RGBA tuple validation, which are common in plotting workflows. The optimizations are most beneficial when processing many color inputs or when_is_single_string_coloris called frequently, making this especially valuable for plotting operations that handle multiple colors or are called repeatedly.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_is_single_color-mir1yojhand push.