⚡️ Speed up function find_last_node by 9,058%#263
Closed
codeflash-ai[bot] wants to merge 1 commit intomainfrom
Closed
⚡️ Speed up function find_last_node by 9,058%#263codeflash-ai[bot] wants to merge 1 commit intomainfrom
find_last_node by 9,058%#263codeflash-ai[bot] wants to merge 1 commit intomainfrom
Conversation
The optimized code achieves a **9057% speedup** (from 12.3ms to 134μs) by replacing a **quadratic O(N×M) algorithm with a linear O(N+M) algorithm**, where N is the number of nodes and M is the number of edges.
**Key optimization:**
The original code uses a nested loop structure: for each node, it iterates through *all* edges to check if that node appears as a source. This results in O(N×M) comparisons.
The optimized version builds a **set of source IDs** from edges in a single pass (`sources = {e["source"] for e in edges}`), then performs O(1) membership checks (`n["id"] not in sources`) for each node. This reduces complexity to O(N+M).
**Why this is faster:**
- **Set lookup is O(1)** vs. linear scan through all edges
- For the large test cases (500 nodes, 499 edges), the original performs ~250,000 comparisons while the optimized performs ~1,000 operations
- Test results confirm this: `test_large_scale_chain_flow` shows **16,642% speedup** (4.43ms → 26.5μs) and `test_large_complete_graph_with_sink` shows **10,155% speedup** (1.62ms → 15.8μs)
**Edge case handling:**
The optimization includes safeguards:
1. **Single-use iterators**: Detects if `edges` is a consumed iterator (`iter(edges) is edges`) and falls back to original logic to preserve correctness
2. **Unhashable sources**: If any source value can't be hashed (e.g., lists, dicts), catches `TypeError` and falls back to the original nested approach
**Performance impact:**
- Small graphs (2-10 nodes): **30-96% faster** - modest gains due to set construction overhead
- Medium graphs (100-300 nodes): **2,834-10,155% faster** - substantial wins as quadratic cost dominates
- Large graphs (500+ nodes): **16,000%+ faster** - dramatic improvements where the original becomes prohibitively slow
The optimization is particularly valuable when `find_last_node` is called repeatedly on non-trivial graphs, as the linear algorithm scales far better than the quadratic baseline.
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.
📄 9,058% (90.58x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
12.3 milliseconds→134 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 9057% speedup (from 12.3ms to 134μs) by replacing a quadratic O(N×M) algorithm with a linear O(N+M) algorithm, where N is the number of nodes and M is the number of edges.
Key optimization:
The original code uses a nested loop structure: for each node, it iterates through all edges to check if that node appears as a source. This results in O(N×M) comparisons.
The optimized version builds a set of source IDs from edges in a single pass (
sources = {e["source"] for e in edges}), then performs O(1) membership checks (n["id"] not in sources) for each node. This reduces complexity to O(N+M).Why this is faster:
test_large_scale_chain_flowshows 16,642% speedup (4.43ms → 26.5μs) andtest_large_complete_graph_with_sinkshows 10,155% speedup (1.62ms → 15.8μs)Edge case handling:
The optimization includes safeguards:
edgesis a consumed iterator (iter(edges) is edges) and falls back to original logic to preserve correctnessTypeErrorand falls back to the original nested approachPerformance impact:
The optimization is particularly valuable when
find_last_nodeis called repeatedly on non-trivial graphs, as the linear algorithm scales far better than the quadratic baseline.✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mkq2j701and push.