⚡️ Speed up function diverging_palette by 45%
#73
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.
📄 45% (0.45x) speedup for
diverging_paletteinsrc/bokeh/palettes.py⏱️ Runtime :
1.63 milliseconds→1.12 milliseconds(best of43runs)📝 Explanation and details
The optimized code achieves a 45% speedup through two key optimizations in the
linear_palettefunction:1. Fast-path for exact matches: Added an early return
if n == len(palette): return tuple(palette)that avoids all computation when requesting the same number of colors as the input palette. This optimization shows dramatic gains in test cases liketest_large_scale_balanced(2014% faster) wherenequals the palette length.2. Vectorized NumPy operations: Replaced the generator expression
tuple(palette[math.floor(i)] for i in np.linspace(...))with pre-computed NumPy operations:indices = np.floor(np.linspace(...)).astype(int)followed bytuple(palette[i] for i in indices). This eliminates the overhead of callingmath.floor()for each element in the Python loop and leverages NumPy's optimized C implementations.The line profiler shows the critical optimization impact: the original's expensive generator expression (99% of function time, 5.55ms) is replaced by two more efficient operations (50.3% + 46.7% of function time, totaling 2.99ms).
These optimizations are particularly effective for:
diverging_palettewherelinear_paletteis called twice per invocationThe optimization maintains identical behavior and error handling while providing consistent performance improvements across all test scenarios.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
unit/bokeh/test_palettes.py::test_cmap_generator_function🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-diverging_palette-mhbgmt7gand push.