⚡️ Speed up method LinearSegmentedColormap.resampled by 10%
#243
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.
📄 10% (0.10x) speedup for
LinearSegmentedColormap.resampledinlib/matplotlib/colors.py⏱️ Runtime :
83.9 microseconds→76.5 microseconds(best of117runs)📝 Explanation and details
The optimization achieves a 9% speedup by reducing attribute lookup overhead through local variable caching. The key changes are:
What was optimized:
self._segmentdata,self.name, and the three_rgba_*attributes into local variables before the constructor callWhy this improves performance:
In Python, attribute access (
self.attribute) involves dictionary lookups that are more expensive than local variable access. The original code performed multipleself.*lookups during object construction and assignment. By caching these values as local variables, the optimization eliminates repeated attribute resolution overhead.Performance impact analysis:
The line profiler shows the constructor call (
LinearSegmentedColormap(...)) remains the dominant cost at ~60% of total time in both versions, but the overall method runtime improved from 83.9μs to 76.5μs. The test results consistently show 5-17% improvements across various scenarios, with larger improvements for edge cases like zero/negative lutsize and complex segmentdata.When this optimization matters most:
The optimization is particularly effective because
resampled()is likely called frequently during matplotlib's rendering pipeline, making even small per-call improvements accumulate meaningfully.✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_colors.py::test_resampled🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-LinearSegmentedColormap.resampled-mja1k6qsand push.