Commit d305de8
authored
Optimize generate_candidates
The optimized code achieves a **4182% speedup** by eliminating expensive Path object creation and manipulation within the loop.
**Key optimizations:**
1. **Pre-compute path parts**: Instead of repeatedly calling `current_path.parent` and creating new Path objects, the code uses `source_code_path.parts` to get all path components upfront as a tuple.
2. **Replace Path operations with string concatenation**: The original code's bottleneck was `(Path(current_path.name) / last_added).as_posix()` which created Path objects and converted them to POSIX format in every iteration. The optimized version uses simple f-string formatting: `f"{parts[i]}/{last_added}"`.
3. **Index-based iteration**: Rather than walking up the directory tree using `current_path.parent`, it uses a reverse range loop over the parts indices, which is much faster than Path navigation.
**Performance impact by test case type:**
- **Deeply nested paths** see the most dramatic improvements (up to 7573% faster for 1000-level nesting) because they eliminate the most Path object creations
- **Simple 1-2 level paths** still benefit significantly (200-400% faster) from avoiding even a few Path operations
- **Edge cases** with special characters or unicode maintain the same speedup ratios, showing the optimization is universally effective
The line profiler confirms the original bottleneck: 94.3% of time was spent on Path object creation (`candidate_path = (Path(current_path.name) / last_added).as_posix()`), which is now replaced with lightweight string operations.1 parent f978a40 commit d305de8
1 file changed
+15
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
44 | 44 | | |
45 | 45 | | |
46 | 46 | | |
47 | | - | |
48 | | - | |
49 | | - | |
50 | | - | |
51 | | - | |
52 | | - | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
53 | 61 | | |
54 | 62 | | |
55 | | - | |
56 | 63 | | |
| 64 | + | |
57 | 65 | | |
58 | 66 | | |
59 | 67 | | |
| |||
0 commit comments