Commit 11bace3
authored
⚡️ Speed up function
Here's an optimized version of your program focusing on reducing per-node overhead and the significant cost of calling `ast.iter_child_nodes(node)` inside your traversal loop (which accounts for almost **80% of total runtime**).
## Optimization Strategies
- **Inline** the implementation of `ast.iter_child_nodes` instead of calling the function for every node. This saves significant overhead (as the stdlib implementation uses `getattr`, a generator and repeated attribute accesses).
- **Use a deque** for stack to benefit from very fast pops from the right end instead of pop from a Python list.
- **Use local variable lookups** wherever possible (`stack_pop = stack.pop` trick) to avoid repeated attribute access on the hot path.
- Do **not** break the function signature or semantics.
---
---
## Summary of improvements
- **No generator allocation or function call for each child visit:** `fast_iter_child_nodes` is inlined and avoids unnecessary attribute access inside collections.
- **Deque** is much faster for stack pops than a Python list.
- Reused bound methods for stack operations to minimize attribute lookup overhead.
- **No change** in output, preserves semantics, and still stops immediately after first `Return`.
This rewrite will make a significant speed difference especially for large function bodies.function_has_return_statement by 41%1 parent 2185af9 commit 11bace3
1 file changed
+19
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
5 | 5 | | |
6 | 6 | | |
7 | 7 | | |
8 | | - | |
| 8 | + | |
9 | 9 | | |
10 | 10 | | |
11 | 11 | | |
| |||
602 | 602 | | |
603 | 603 | | |
604 | 604 | | |
605 | | - | |
606 | | - | |
| 605 | + | |
| 606 | + | |
| 607 | + | |
| 608 | + | |
| 609 | + | |
| 610 | + | |
| 611 | + | |
| 612 | + | |
| 613 | + | |
| 614 | + | |
| 615 | + | |
| 616 | + | |
| 617 | + | |
| 618 | + | |
| 619 | + | |
| 620 | + | |
607 | 621 | | |
608 | | - | |
| 622 | + | |
609 | 623 | | |
610 | 624 | | |
611 | | - | |
| 625 | + | |
612 | 626 | | |
613 | 627 | | |
614 | 628 | | |
| |||
0 commit comments