⚡️ Speed up method Categorical._rank by 14%
#102
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.
📄 14% (0.14x) speedup for
Categorical._rankinpandas/core/arrays/categorical.py⏱️ Runtime :
2.56 milliseconds→2.26 milliseconds(best of79runs)📝 Explanation and details
The optimized code achieves a 13% speedup through two key optimizations that eliminate overhead in hot code paths:
Key Optimizations Applied
1. Streamlined
rank()Function inalgorithms.py_ensure_data()call overhead: Replaced the expensive function call (855μs per call) with inline conversion logic usingnp.asarray()only when neededvalues.dtypeandvalues.ndimin variables to avoid repeated property lookupsndimdirectly without additional preprocessing since 1D arrays are the most common case2. Property Caching in
_values_for_rank()self.ordered,self.codes, andself.categoriesin local variables upfront to avoid expensive attribute lookups in conditional branchescodesdirectly instead of callingnp.array(self), which creates unnecessary array conversionsPerformance Impact by Test Case
The optimizations show particularly strong gains for:
np.array(self)conversionThe optimizations are most effective for unordered categoricals with numeric categories and large datasets, while maintaining identical correctness across all test scenarios.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Categorical._rank-mhbwq18hand push.