⚡️ Speed up method Styler._map by 10%
#408
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.
📄 10% (0.10x) speedup for
Styler._mapinpandas/io/formats/style.py⏱️ Runtime :
19.6 milliseconds→17.7 milliseconds(best of13runs)📝 Explanation and details
The optimized code achieves a 10% performance improvement by targeting key bottlenecks in the
_update_ctxmethod and making a minor optimization in_map.Key Optimizations Applied:
Pre-computed column lookups: Instead of calling
self.columns.get_loc(cn)for each column in every iteration, the optimized version pre-computes all column locations in a dictionary (columns_get_loc) at the start. This eliminates repeated expensive index lookups.Direct array access: The optimization uses
attrs.valuesandattrs.indexto access the underlying NumPy array data directly, avoiding the overhead of DataFrame column extraction (attrs[cn]) which was taking significant time in the original implementation.Improved null checking: The original code used
not c or pd.isna(c)which could be inefficient. The optimized version checks for common falsy values (c is None or c == "") first before falling back topd.isna(c), providing a fast path for the most common cases.Conditional functools.partial: In
_map, the optimization avoids creating afunctools.partialwrapper when no kwargs are provided (the common case), using the function directly instead.Why These Optimizations Work:
Impact on Workloads:
The optimizations are particularly effective for:
The improvements maintain full backward compatibility and preserve all existing behavior while significantly reducing the computational cost of common styling workflows.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Styler._map-mj9xqj6mand push.