⚡️ Speed up method Graph.topologicalSort by 63%#886
Closed
codeflash-ai[bot] wants to merge 1 commit into
Closed
Conversation
The optimization achieves a **63% speedup** by replacing expensive O(n) list insertions with efficient O(1) appends, then performing a single reverse operation. **Key optimization:** - **Original**: Used `stack.insert(0, v)` which requires shifting all existing elements, costing O(n) per insertion - **Optimized**: Uses `stack.append(v)` (O(1)) followed by `stack.reverse()` once at the end **Why this works:** In topological sorting, nodes need to be added in reverse post-order (nodes with no outgoing edges first). The original code achieved this by prepending each node, but this is inefficient. The optimized version appends nodes during traversal, then reverses the entire list once - transforming O(n²) insertion complexity to O(n). **Performance impact by graph type:** - **Large graphs benefit most**: Test cases with 1000 nodes show 60-75% speedups (e.g., `test_large_disconnected_graph`: 208μs → 124μs) - **Small graphs see minimal impact**: Basic test cases show 0-4% variance, as the overhead dominates for small inputs - **Dense graphs with many recursive calls**: Show significant gains due to reduced per-insertion cost The line profiler confirms this: `stack.insert(0, v)` took 1.7% of total time with high per-hit cost (374.4ns), while `stack.append(v)` takes only 1.2% with lower per-hit cost (318.3ns), despite the added reverse operation. This optimization is particularly valuable for algorithms processing large graphs where topological sorting is called frequently.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
📄 63% (0.63x) speedup for
Graph.topologicalSortincode_to_optimize/topological_sort.py⏱️ Runtime :
9.76 milliseconds→5.97 milliseconds(best of20runs)📝 Explanation and details
The optimization achieves a 63% speedup by replacing expensive O(n) list insertions with efficient O(1) appends, then performing a single reverse operation.
Key optimization:
stack.insert(0, v)which requires shifting all existing elements, costing O(n) per insertionstack.append(v)(O(1)) followed bystack.reverse()once at the endWhy this works:
In topological sorting, nodes need to be added in reverse post-order (nodes with no outgoing edges first). The original code achieved this by prepending each node, but this is inefficient. The optimized version appends nodes during traversal, then reverses the entire list once - transforming O(n²) insertion complexity to O(n).
Performance impact by graph type:
test_large_disconnected_graph: 208μs → 124μs)The line profiler confirms this:
stack.insert(0, v)took 1.7% of total time with high per-hit cost (374.4ns), whilestack.append(v)takes only 1.2% with lower per-hit cost (318.3ns), despite the added reverse operation.This optimization is particularly valuable for algorithms processing large graphs where topological sorting is called frequently.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_topological_sort.py::test_topological_sorttest_topological_sort.py::test_topological_sort_2test_topological_sort.py::test_topological_sort_3🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_ofw5g32s/tmpvz1r45nf/test_concolic_coverage.py::test_Graph_topologicalSortTo edit these changes
git checkout codeflash/optimize-Graph.topologicalSort-mhpg8x3oand push.