⚡️ Speed up function _infer_docstring_style
by 31%
#32
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.
📄 31% (0.31x) speedup for
_infer_docstring_style
inpydantic_ai_slim/pydantic_ai/_griffe.py
⏱️ Runtime :
6.08 milliseconds
→4.64 milliseconds
(best of109
runs)📝 Explanation and details
Here’s how to optimize your
_infer_docstring_style
function for both speed and memory usage.any()
for inner loop: Instead of using a generator expression (which creates a generator and then iterates inany()
), a simplefor
loop with early break is slightly faster and allows us to exit on the first match directly._docstring_style_patterns
data comes from a read-only module, we will compile on demand within the function, but cache them locally with a simpledict
for future calls (i.e., LRU caching for compiled regex)..format
calls: Pre-formatting patterns (for all replacements) and re-using if this function is called many times.Notes.
_regex_cache
dict to ensure each compiled regex is re-used, speeding up repeated style checks.This version is optimal for both single calls and repeated calls (where the caching shines).
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_infer_docstring_style-mdeycsff
and push.