⚡️ Speed up function _get_indentation_of_key by 17%
#176
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.
📄 17% (0.17x) speedup for
_get_indentation_of_keyinmlflow/utils/docstring_utils.py⏱️ Runtime :
76.2 microseconds→64.8 microseconds(best of65runs)📝 Explanation and details
The optimization replaces a conditional expression with an early return pattern and swaps the operand order in string multiplication. Here's why it's faster:
Key Optimizations:
Early return for common cases: The optimized version immediately returns
""whenindex <= 0(covering both not-found cases whereindex == -1and zero-indentation cases whereindex == 0). This avoids the overhead of string multiplication entirely for these frequent scenarios.Operand order optimization: Changed from
index * " "to" " * index. In CPython, left-multiplication of strings by integers (str * int) is more optimized than right-multiplication (int * str), as the string object can directly handle the repetition internally.Performance Impact by Test Case:
find()dominates runtimeHot Path Context:
Based on
function_references, this function is called from_replace_all()in docstring processing, where it runs in a loop over multiple replacements. The optimization is particularly valuable here because:The 17% overall speedup makes this optimization worthwhile for MLflow's docstring processing pipeline, especially given the function's usage in text replacement workflows.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_get_indentation_of_key-mhx7axwzand push.