⚡️ Speed up method SelectionMixin._infer_selection by 13%
#381
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.
📄 13% (0.13x) speedup for
SelectionMixin._infer_selectioninpandas/core/base.py⏱️ Runtime :
81.6 microseconds→71.9 microseconds(best of250runs)📝 Explanation and details
The optimization achieves a 13% speedup by eliminating redundant function calls and restructuring control flow for better performance characteristics.
Key Optimizations Applied:
Eliminated Redundant
lib.is_scalar()Calls: The original code calledlib.is_scalar(key)up to twice - once in the DataFrame path and once in the Series path. The optimized version calls it once and reuses the result, saving expensive function call overhead.Short-Circuit Logic for DataFrame Path: Restructured the DataFrame condition logic to avoid expensive
key in subsetoperations when unnecessary. The original code always evaluated bothlib.is_scalar(key) and key in subsetandlib.is_list_like(key)in a compound OR expression. The optimized version checks scalar first, then only checkskey in subsetif the key is scalar, avoiding this lookup for non-scalar keys.Early Returns: Replaced the pattern of setting a
selectionvariable and returning it at the end with direct returns, reducing variable assignments and improving control flow efficiency.Performance Impact by Test Case:
key in subsetcheck entirelyis_scalarcallThe optimization is particularly effective for common scenarios where scalar keys are used with DataFrames, making this a worthwhile performance enhancement for a frequently-called method in pandas' selection infrastructure.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-SelectionMixin._infer_selection-mio2t65pand push.