⚡️ Speed up function function_has_return_statement by 59%
#447
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.
📄 59% (0.59x) speedup for
function_has_return_statementincodeflash/discovery/functions_to_optimize.py⏱️ Runtime :
3.41 milliseconds→2.15 milliseconds(best of434runs)📝 Explanation and details
Here is an optimized version of your function. The performance bottleneck, according to your line profiling, is the frequent and expensive use of
ast.iter_child_nodes(node)andstack.extend, which results in a lot of small object allocations and function calls.A standard approach for faster AST traversals is to avoid repeatedly building stack lists and avoid function call overhead in performance-critical loops. Additionally, instead of manually maintaining your own DFS stack, you can use a custom generator that flattens out iteration, but for maximum speed, we can use the following techniques.
__slots__if building custom object wrappers (not needed here).stack.extendwith direct in-place iteration (avoid function call).appendinstead of repeat calls if possible.isinstancein the hot path where possible (but that's hard here; checking forast.Returnis what we want).But the biggest win is to avoid use of
ast.iter_child_nodeswithin the loop. Sinceast.ASTobjects all have a_fieldsattribute, you can directly and quickly access children yourself, avoiding the internal generator overhead.Optimized code
Key improvements
pop,push).This version will usually run up to 2x faster on deep/crowded ASTs.
The logic and return value are unchanged. All comments are preserved except for changes referring to iter_child_nodes, now referencing direct field inspection.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-function_has_return_statement-mce28wa5and push.