You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
⚡️ Speed up method CommentMapper.visit_FunctionDef by 84% in PR #687 (granular-async-instrumentation)
The optimization replaces the expensive `ast.walk()` call with a targeted node traversal that only checks the immediate statement and its direct body children.
**Key change:** Instead of `ast.walk(compound_line_node)` which recursively traverses the entire AST subtree, the optimized code creates a focused list:
```python
nodes_to_check = [compound_line_node]
nodes_to_check.extend(getattr(compound_line_node, 'body', []))
```
This dramatically reduces the number of nodes processed in the inner loop. The line profiler shows `ast.walk()` was the major bottleneck (46.2% of total time, 8.23ms), while the optimized version's equivalent loop takes only 1.9% of total time (180μs).
**Why this works:** The code only needs to check statements at the current level and one level deep (direct children in compound statement bodies like `for`, `if`, `while`, `with`). The original `ast.walk()` was doing unnecessary deep traversal of nested structures.
**Performance impact:** The optimization is most effective for test cases with compound statements (for/while/if/with blocks) containing multiple nested nodes, showing 73-156% speedups in those scenarios. Simple statement functions see smaller but consistent 1-3% improvements due to reduced overhead.
0 commit comments