Commit 737cb58
authored
Optimize CommentMapper.visit_AsyncFunctionDef
The optimized code achieves a 10% speedup through several key micro-optimizations that reduce overhead in the performance-critical loops:
**Key Optimizations:**
1. **Hoisted repeated attribute lookups**: Variables like `node_body = node.body`, `original_runtimes = self.original_runtimes`, and `results = self.results` are cached once outside the loops instead of being accessed repeatedly via `self.` attribute lookups.
2. **Cached type objects and method references**: `isinstance_stmt = ast.stmt`, `isinstance_control = (ast.With, ast.For, ast.While, ast.If)`, and `get_comment = self.get_comment` eliminate repeated global/attribute lookups in the hot loops.
3. **Improved string formatting**: Replaced string concatenation (`str(i) + "_" + str(j)`) with f-string formatting (`f"{i}_{j}"`) which is more efficient in Python.
4. **Optimized getattr usage**: Changed `getattr(compound_line_node, "body", [])` to `getattr(compound_line_node, "body", None)` with a conditional check, avoiding list creation when no body exists.
**Why it's faster**: The profiler shows the main performance bottleneck is in the nested loops processing control flow statements. By eliminating repetitive attribute lookups and method calls that happen thousands of times (2,729 iterations in the outer loop, 708 in nested loops), the optimization reduces per-iteration overhead.
**Test case performance**: The optimizations show the biggest gains on large-scale test cases with many statements (9-22% faster) and mixed control blocks, while having minimal impact on simple cases with few statements (often slightly slower due to setup overhead).1 parent 40c4108 commit 737cb58
1 file changed
+38
-16
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
61 | 61 | | |
62 | 62 | | |
63 | 63 | | |
64 | | - | |
| 64 | + | |
| 65 | + | |
65 | 66 | | |
66 | | - | |
| 67 | + | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
| 71 | + | |
| 72 | + | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
| 76 | + | |
| 77 | + | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
| 81 | + | |
| 82 | + | |
67 | 83 | | |
68 | | - | |
69 | | - | |
70 | | - | |
| 84 | + | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| 88 | + | |
71 | 89 | | |
72 | | - | |
| 90 | + | |
| 91 | + | |
73 | 92 | | |
74 | | - | |
| 93 | + | |
| 94 | + | |
| 95 | + | |
75 | 96 | | |
76 | | - | |
77 | | - | |
78 | | - | |
79 | | - | |
80 | | - | |
| 97 | + | |
| 98 | + | |
| 99 | + | |
| 100 | + | |
| 101 | + | |
| 102 | + | |
81 | 103 | | |
82 | 104 | | |
83 | 105 | | |
84 | | - | |
85 | | - | |
86 | | - | |
| 106 | + | |
| 107 | + | |
| 108 | + | |
87 | 109 | | |
88 | | - | |
| 110 | + | |
89 | 111 | | |
90 | 112 | | |
91 | 113 | | |
| |||
0 commit comments