Commit bac75e2
authored
Optimize AsyncCallInstrumenter._instrument_statement
The optimized code achieves an 11% speedup by replacing the expensive `ast.walk()` with a custom stack-based traversal that supports **early termination**.
**Key optimizations:**
1. **Stack-based AST traversal with early exit**: Instead of `ast.walk()` which must visit every node, the optimized version uses a manual stack that immediately returns `True` when finding a matching `Await` node, avoiding unnecessary traversal of remaining subtrees.
2. **Function name caching**: Pre-stores `self._function_name = function.function_name` in `__init__` to eliminate repeated attribute lookups in `_is_target_call()`.
3. **Local variable optimization**: Extracts `func = call_node.func` to reduce repeated attribute access.
**Performance impact by test type:**
- **Small/simple statements** (basic tests): 27-106% faster due to reduced traversal overhead
- **Complex nested expressions**: 14% improvement as early exit helps when matches are found
- **Large-scale scenarios**: 6-22% improvement, with better gains when fewer matches occur (early termination is more effective)
The optimization is most effective when matches are found early in the AST traversal, as it can skip examining the remaining nodes entirely. Line profiling shows the stack-based approach reduces the expensive `ast.walk()` overhead from 29% to 21.5% of total time in `_instrument_statement`.1 parent 2c97b92 commit bac75e2
1 file changed
+17
-8
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
312 | 312 | | |
313 | 313 | | |
314 | 314 | | |
| 315 | + | |
| 316 | + | |
315 | 317 | | |
316 | 318 | | |
317 | 319 | | |
| |||
397 | 399 | | |
398 | 400 | | |
399 | 401 | | |
400 | | - | |
| 402 | + | |
| 403 | + | |
| 404 | + | |
| 405 | + | |
| 406 | + | |
401 | 407 | | |
402 | 408 | | |
403 | 409 | | |
404 | 410 | | |
405 | 411 | | |
406 | 412 | | |
407 | | - | |
408 | 413 | | |
409 | | - | |
| 414 | + | |
| 415 | + | |
| 416 | + | |
410 | 417 | | |
411 | 418 | | |
412 | 419 | | |
413 | 420 | | |
414 | | - | |
415 | | - | |
416 | | - | |
417 | | - | |
| 421 | + | |
| 422 | + | |
| 423 | + | |
| 424 | + | |
| 425 | + | |
| 426 | + | |
418 | 427 | | |
419 | 428 | | |
420 | 429 | | |
| 430 | + | |
421 | 431 | | |
422 | 432 | | |
423 | | - | |
424 | 433 | | |
425 | 434 | | |
426 | 435 | | |
| |||
0 commit comments