Commit ec6f0a2
authored
⚡️ Speed up function
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)` and `stack.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.
- Use `__slots__` if building custom object wrappers (not needed here).
- **Replace `stack.extend` with direct in-place iteration** (avoid function call).
- Use a tuple for `append` instead of repeat calls if possible.
- Live with the stack, but **reduce attr lookups** by caching methods.
- Avoid `isinstance` in the hot path where possible (but that's hard here; checking for `ast.Return` is what we want).
But the biggest win is to avoid use of `ast.iter_child_nodes` within the loop. Since `ast.AST` objects all have a `_fields` attribute, you can directly and quickly access children yourself, avoiding the internal generator overhead.
#### Optimized code
### Key improvements
- **Avoid expensive ast.iter_child_nodes** in the loop.
- **Reduce attribute lookups** by caching local variables (`pop`, `push`).
- **Directly scan node fields** to find children.
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.function_has_return_statement by 59%1 parent 639e42e commit ec6f0a2
1 file changed
+13
-2
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
604 | 604 | | |
605 | 605 | | |
606 | 606 | | |
| 607 | + | |
| 608 | + | |
| 609 | + | |
607 | 610 | | |
608 | | - | |
| 611 | + | |
609 | 612 | | |
610 | 613 | | |
611 | | - | |
| 614 | + | |
| 615 | + | |
| 616 | + | |
| 617 | + | |
| 618 | + | |
| 619 | + | |
| 620 | + | |
| 621 | + | |
| 622 | + | |
612 | 623 | | |
613 | 624 | | |
614 | 625 | | |
| |||
0 commit comments