Commit 378bd1b
authored
Optimize CommentMapper.visit_FunctionDef
The optimized code achieves a 10% speedup through several targeted micro-optimizations that reduce overhead in the tight loops:
**Key optimizations:**
1. **Local variable caching for frequent lookups**: Storing `self.original_runtimes` and `self.optimized_runtimes` in local variables (`original_runtimes`, `optimized_runtimes`) eliminates repeated attribute lookups in the inner loops, which is expensive due to Python's method resolution.
2. **Eliminated unnecessary list allocations**: The original code created `nodes_to_check = [compound_line_node]` and extended it with `getattr(compound_line_node, "body", [])` on every iteration. The optimized version uses `hasattr()` to check for a body attribute first, then iterates directly over `compound_line_node.body` when present, avoiding list creation and extension.
3. **Reduced redundant attribute access**: Added `nbody = node.body` and `line_body = line_node.body` to cache commonly accessed attributes, reducing repeated lookups.
4. **Streamlined f-string usage**: Consistent use of f-strings (`f"{i}_{j}"` instead of `str(i) + "_" + str(j)`) provides marginal performance improvements for string concatenation.
The optimizations are most effective for **large-scale test cases** - the annotated tests show the biggest improvements (13.4% faster) occur with functions containing many compound statements (50 for-loops with 10 statements each), where the eliminated allocations and attribute lookups compound significantly. Simple functions show minimal or slight performance regression due to the overhead of additional local variable assignments, but complex functions with nested loops see substantial gains.1 parent 7e4ecb3 commit 378bd1b
1 file changed
+25
-14
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 | + | |
67 | 71 | | |
68 | | - | |
| 72 | + | |
69 | 73 | | |
70 | | - | |
| 74 | + | |
| 75 | + | |
71 | 76 | | |
72 | | - | |
73 | | - | |
74 | | - | |
75 | | - | |
76 | | - | |
77 | | - | |
78 | | - | |
79 | | - | |
80 | | - | |
| 77 | + | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
| 81 | + | |
| 82 | + | |
| 83 | + | |
| 84 | + | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| 88 | + | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
81 | 92 | | |
82 | 93 | | |
83 | 94 | | |
84 | | - | |
85 | | - | |
| 95 | + | |
| 96 | + | |
86 | 97 | | |
87 | 98 | | |
88 | 99 | | |
| |||
0 commit comments