⚡️ Speed up function get_grid_style by 110%
#105
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.
📄 110% (1.10x) speedup for
get_grid_styleinplotly/matplotlylib/mplexporter/utils.py⏱️ Runtime :
3.98 milliseconds→1.90 milliseconds(best of417runs)📝 Explanation and details
Here's an optimized version of your Python program, targeting your main bottleneck: export_color. From your line profile, most of the runtime is dominated by repeated calls to
colorConverter.to_rgbaandcolorConverter.to_rgb. These functions are pure (for a specific color input always outputting the same results), so caching their outputs aggressively will drastically reduce redundant computations, especially since your usage pattern suggests strong color locality (repeated calls with the same argument).Other minor tweaks.
",".join(map(str, ...))inget_dasharraywith a faster list comprehension._dashSeqand in function calls (minor but measurable).export_color, avoid calling bothto_rgbaandto_rgbfor alpha==1; just slice the values from the first result, keeping only one converter call (sinceto_rgbais a superset ofto_rgb).np.round(val * 255)withint(round(val * 255))and avoid extrastrconversion steps.Here is the rewritten, optimized code.
Summary of major optimizations:
@lru_cachedecorators for color conversions.This rewrite should provide a significant speed up—especially in
export_color, cascading intoget_grid_style, which the profiler showed as the main hot spot.✅ Correctness verification report:
🌀 Generated Regression Tests Details
To edit these changes
git checkout codeflash/optimize-get_grid_style-mb27tu6yand push.