⚡️ Speed up function get_return_docstring by 68%
#71
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.
📄 68% (0.68x) speedup for
get_return_docstringingradio/cli/commands/components/_docs_utils.py⏱️ Runtime :
1.53 milliseconds→906 microseconds(best of39runs)📝 Explanation and details
The optimization precompiles the regular expression pattern into a reusable compiled regex object (
_RETURN_PATTERN), eliminating the need to recompile the pattern on every function call.Key changes:
re.compile()with the same pattern and flags{0,1}to?for better readability.search()method instead ofre.search()Why this leads to speedup:
In Python,
re.search()must parse and compile the regex pattern each time it's called. By precompiling the pattern once at module load time, we eliminate this compilation overhead on every function invocation. The line profiler shows the regex search operation (line withre.search) dropped from 91.9% of execution time to 83.1%, with per-hit time reducing from 22,435ns to 8,469ns - a 62% improvement on the most expensive operation.Performance impact based on function references:
The
get_return_docstringfunction is called withinextract_docstrings(), which processes multiple class members and their docstrings in a loop. Since documentation parsing typically processes many functions/methods in batch operations, this optimization compounds significantly - each avoided regex compilation saves ~14μs per call.Test case performance:
The optimization shows consistent 100-200% speedup across all test cases, with particularly strong gains on edge cases like empty strings (580% faster) and simple cases (130-180% faster). Large-scale tests show smaller but meaningful improvements (4-30% faster), indicating the optimization remains effective even when regex compilation becomes a smaller fraction of total processing time for very large inputs.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-get_return_docstring-mhwvp5krand push.