⚡️ Speed up method FunctionCallFinder._extract_source_code by 295%
#838
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.
📄 295% (2.95x) speedup for
FunctionCallFinder._extract_source_codeincodeflash/code_utils/code_extractor.py⏱️ Runtime :
652 microseconds→165 microseconds(best of45runs)📝 Explanation and details
The optimized code achieves a 295% speedup through several key optimizations in the
_extract_source_codemethod:1. Early Exit Optimization in Min Indent Finding
The most significant improvement is adding an early exit when
min_indentreaches 0:This eliminates unnecessary iterations when processing functions with no indentation, which is common for top-level functions.
2. Caching Strip Operation
Instead of calling
line.strip()multiple times, the optimized version caches it:This reduces redundant string operations during the min indent calculation loop.
3. Conditional List Comprehension with Fallbacks
The optimized code replaces nested loops with list comprehensions but only when beneficial:
When no processing is needed, it uses the faster
list(func_lines)instead of applying transformations.Performance Impact by Test Case:
The optimizations are particularly effective for large codebases and functions with minimal indentation (top-level functions), which are common in real-world code analysis scenarios.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-FunctionCallFinder._extract_source_code-mgzs0zwwand push.