Commit a1c8596
authored
Optimize Graph.topologicalSort
The optimization achieves a **62% speedup** by eliminating a critical performance bottleneck in list operations during the depth-first traversal.
**Key optimization:** The original code used `stack.insert(0, v)` to maintain topological order, which is an O(n) operation for each node since it shifts all existing elements. The optimized version uses `stack.append(v)` (O(1)) and performs a single `stack.reverse()` (O(n)) at the end.
**Performance impact:** For a graph with n nodes, this changes the time complexity from O(n²) for stack operations to O(n). The line profiler shows this dramatically - `stack.insert(0, v)` took 3.1ms with 335.9ns per hit in the original, while `stack.append(v)` takes only 2.3ms with 245.8ns per hit, plus a negligible one-time reverse operation.
**Additional micro-optimization:** Changed `visited[i] == False` to `not visited[i]`, which is slightly more efficient as it avoids the equality comparison operator.
**Test case benefits:** The optimization shows the most dramatic gains on larger graphs:
- Large sparse graphs: 63-67% faster
- Binary trees and multi-component graphs: 63-69% faster
- Dense graphs with many nodes: 87% faster for all-to-one connectivity
For small graphs (≤10 nodes), improvements are modest (1-7%) since the overhead difference is minimal, but the optimization scales excellently with graph size, making it particularly valuable for real-world applications processing large dependency graphs or network structures.1 parent 42b4637 commit a1c8596
1 file changed
+4
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
14 | 14 | | |
15 | 15 | | |
16 | 16 | | |
17 | | - | |
| 17 | + | |
18 | 18 | | |
19 | | - | |
20 | | - | |
| 19 | + | |
21 | 20 | | |
22 | 21 | | |
23 | 22 | | |
24 | 23 | | |
25 | 24 | | |
26 | 25 | | |
27 | 26 | | |
28 | | - | |
| 27 | + | |
29 | 28 | | |
30 | 29 | | |
| 30 | + | |
31 | 31 | | |
0 commit comments