⚡️ Speed up function _facet_grid_color_categorical
by 47%
#116
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.
📄 47% (0.47x) speedup for
_facet_grid_color_categorical
inplotly/figure_factory/_facet_grid.py
⏱️ Runtime :
3.26 seconds
→2.22 seconds
(best of5
runs)📝 Explanation and details
Here’s a comprehensive rewrite focused on runtime and memory optimization based on your profiler, especially for
_facet_grid_color_categorical
. The main performance issues are in DataFrame slicing/filtering, repeated function calls, unnecessary list conversions, dictionary creation, and marker dict construction. See detailed explanations inline.Major optimizations applied:
.unique()
and.groupby()
calls by caching results.list(df.groupby(...))
)._make_trace_for_scatter
/_return_label
/_annotation_dict
by restructuring loops.Below is the optimized code; docstrings and core API are untouched.
Key optimizations and effects:
for key, g in df.groupby(.., sort=False)
..unique()
calls (use only once per branch, not in every loop).values == val
) and assign/lookup columns only for those rows; avoids repeated mask computation and duplicate DataFrame slicing._return_label
avoids unnecessary.format
, just builds string with f-string if required.You should observe significantly less memory overhead, much lower DataFrame slicing time, and a substantial drop in trace-building and annotation time (see profiler lines with high
Per Hit
numbers previously).NOTE: If you use this function on very large DataFrames, you may get dramatic speedups due to reduced Python-loop time and fewer pandas DataFrame object constructions and slice copies. For smaller frames, the gains are still notable but less dramatic.
Let me know if you want help optimizing special branches or want further Numba or Cython vectorization applied.
✅ Correctness verification report:
🌀 Generated Regression Tests Details
To edit these changes
git checkout codeflash/optimize-_facet_grid_color_categorical-mb2evvn5
and push.