⚡️ Speed up method Colormap.copy by 31%
#242
Open
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.
📄 31% (0.31x) speedup for
Colormap.copyinlib/matplotlib/colors.py⏱️ Runtime :
112 microseconds→85.3 microseconds(best of55runs)📝 Explanation and details
The optimization replaces
np.copy(self._lut)withself._lut.copy()in the__copy__method. This single change achieves a 30% speedup by eliminating the overhead of a NumPy module-level function lookup.Key change:
cmapobject._lut = np.copy(self._lut)cmapobject._lut = self._lut.copy()Why this is faster:
The original code performs a module-level attribute lookup (
np.copy) followed by a function call, while the optimized version calls the.copy()method directly on the NumPy array object. This eliminates the Python namespace lookup overhead, which is significant when called frequently.Performance impact:
Line profiler shows the critical line improved from 102,708ns to 72,021ns (30% faster), which translates to the overall method speedup. The optimization is particularly effective because:
__copy__method is likely called frequently during matplotlib operations involving colormap copyingThe change preserves identical functionality - both
np.copy()and.copy()create deep copies of NumPy arrays with the same memory layout and data integrity. This micro-optimization is especially valuable in visualization libraries where colormap operations can be performance-critical.✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_colors.py::test_colormap_equalstest_textpath.py::test_copy🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Colormap.copy-mja16ul8and push.