Commit 4ff9865
authored
Optimize collect_existing_class_names
The optimized code achieves a **350% speedup** (2.36ms → 523μs) by replacing the generic `ast.walk()` traversal with a targeted stack-based iteration that only visits nodes where class definitions can appear.
**Key Performance Improvement:**
The original implementation uses `ast.walk(tree)`, which performs an exhaustive depth-first traversal of **every single node** in the AST—including expressions, literals, operators, and other leaf nodes that can never contain class definitions. For a typical Python module, this means checking thousands of irrelevant nodes.
The optimized version uses a stack-based approach that only descends into structural nodes (ClassDef, FunctionDef, If, For, While, With, Try blocks) where classes can actually be defined. This dramatically reduces the number of nodes visited and `isinstance()` checks performed.
**Why This Matters:**
From the test results, we see consistent 200-700% speedups across all scenarios:
- Empty modules: 579% faster (5.37μs → 791ns) - minimal traversal overhead
- Simple cases: 200-400% faster - fewer nodes to check
- Complex nested structures: 405% faster (37.2μs → 7.37μs) - targeted descent pays off
- Large modules (500 classes): 280% faster (869μs → 228μs) - scales better
- Mixed workloads: 558% faster (799μs → 121μs) - avoids non-class nodes
**Impact on Workloads:**
Based on the function references showing this is called from `build_testgen_context`, this optimization benefits test generation workflows that analyze Python code structure. Since class extraction is likely performed repeatedly during code analysis, the 4x speedup directly improves overall test generation throughput. The optimization is particularly effective for large codebases with many classes and complex nesting patterns, as demonstrated by the benchmark results.1 parent fadf6d4 commit 4ff9865
1 file changed
Lines changed: 22 additions & 1 deletion
Lines changed: 22 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
563 | 563 | | |
564 | 564 | | |
565 | 565 | | |
566 | | - | |
| 566 | + | |
| 567 | + | |
| 568 | + | |
| 569 | + | |
| 570 | + | |
| 571 | + | |
| 572 | + | |
| 573 | + | |
| 574 | + | |
| 575 | + | |
| 576 | + | |
| 577 | + | |
| 578 | + | |
| 579 | + | |
| 580 | + | |
| 581 | + | |
| 582 | + | |
| 583 | + | |
| 584 | + | |
| 585 | + | |
| 586 | + | |
| 587 | + | |
567 | 588 | | |
568 | 589 | | |
569 | 590 | | |
| |||
0 commit comments