Commit 6795847
authored
Optimize _get_parent_type_name
The optimization achieves an **11% runtime improvement** by eliminating repeated tuple construction during membership testing.
**Key Change:**
The original code uses `parent.type in ("ClassDef", "InterfaceDef", "EnumDef")` which creates a new tuple on every iteration of the parent loop. The optimized version replaces this with a module-level constant `_PARENT_TYPE_NAMES = frozenset(("ClassDef", "InterfaceDef", "EnumDef"))`.
**Why This Is Faster:**
1. **Eliminates repeated allocations**: The original code reconstructs the tuple 1,267 times per profiled run (visible in line profiler hits). Each reconstruction involves memory allocation and garbage collection overhead.
2. **Faster membership testing**: `frozenset` uses hash-based O(1) lookups vs. tuple's O(n) linear scan, though with only 3 elements this difference is minimal.
3. **Reduced per-iteration overhead**: The constant is created once at module load time rather than on every loop iteration.
**Performance Profile:**
- Best gains appear in scenarios with **many non-matching parents** (27.2% speedup when scanning 1000 non-matching parents)
- Consistent 5-15% improvements across most test cases
- Particularly effective when the function is called repeatedly in loops, as the constant is shared across all invocations
**Test Results Show:**
- Functions with large parent lists see the biggest improvements (e.g., 27.2% for 1000 non-matching parents, 10.4% for 500 matching classes)
- Minimal overhead (< 3% regression) in edge cases with empty strings or enum-only parents
- The optimization maintains correctness across all test scenarios including unicode names, special characters, and mixed type definitions
The line profiler confirms the hot spot is the membership test line (20.9% of total time), making this micro-optimization worthwhile for a function that may be called frequently during code analysis workflows.1 parent 41b08a9 commit 6795847
1 file changed
Lines changed: 3 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
19 | 19 | | |
20 | 20 | | |
21 | 21 | | |
| 22 | + | |
| 23 | + | |
22 | 24 | | |
23 | 25 | | |
24 | 26 | | |
| |||
137 | 139 | | |
138 | 140 | | |
139 | 141 | | |
140 | | - | |
| 142 | + | |
141 | 143 | | |
142 | 144 | | |
143 | 145 | | |
| |||
0 commit comments