⚡️ Speed up function _highlight_between by 22%
#412
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.
📄 22% (0.22x) speedup for
_highlight_betweeninpandas/io/formats/style.py⏱️ Runtime :
53.9 milliseconds→44.3 milliseconds(best of10runs)📝 Explanation and details
The optimized code achieves a 21% speedup through several key performance improvements in the pandas styling functions:
Key Optimizations:
Smart Type-Specific Handling in
_validate_apply_axis_arg:np.ndarrayinputs to avoid redundantnp.asarray()callsastype(copy=False)for dtype conversion when possible, reducing unnecessary memory copiesdtype = {"dtype": dtype} if dtype else {}todtype_kw = {"dtype": dtype} if dtype is not None else {}for cleaner null checkingReduced Memory Allocations in
_highlight_between:left_array/right_array) only once, avoiding repeated validation callsto_numpy(dtype=bool, copy=False)to ensure all boolean operations work on efficient numpy arraysnp.where()operation only once on pre-computed numpy boolean masks instead of mixed pandas/numpy typesMinimized Branching Overhead:
_validate_apply_axis_argeliminate unnecessary processing for common casesPerformance Impact: The optimizations are particularly effective for test cases with:
The improvements target the most common styling operations while maintaining full backward compatibility and preserving all error handling behavior.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_highlight_between-mja1pcb6and push.