⚡️ Speed up function find_last_node by 6,295%#266
Closed
codeflash-ai[bot] wants to merge 1 commit intomainfrom
Closed
⚡️ Speed up function find_last_node by 6,295%#266codeflash-ai[bot] wants to merge 1 commit intomainfrom
find_last_node by 6,295%#266codeflash-ai[bot] wants to merge 1 commit intomainfrom
Conversation
The optimized code achieves a **6294% speedup** (from 9.89ms to 155μs) by eliminating nested iteration through a fundamental algorithmic improvement.
## Key Optimization
**Original approach:** For each node, the code uses `all(e["source"] != n["id"] for e in edges)` which requires checking every edge for every node - an O(n×m) operation where n is the number of nodes and m is the number of edges.
**Optimized approach:** Pre-computes a set of all source IDs once (`sources = {e["source"] for e in edges}`), then performs O(1) membership checks (`n["id"] not in sources`). This reduces complexity to O(n+m).
## Why This Is Faster
1. **Set lookup vs repeated iteration**: Python set membership tests are O(1) on average, while iterating through all edges for each node is O(m). With multiple nodes, the original approach repeats this m-times traversal n times.
2. **Single pass through edges**: Building the `sources` set requires one pass through edges (38.7% of optimized runtime), but this one-time cost is amortized across all node checks.
3. **Type guard optimization**: The `isinstance()` check ensures we only use the optimized path for reusable collections, falling back to the original logic for iterators that can't be traversed multiple times.
## Performance Characteristics
The optimization excels when:
- **Large graphs**: The test with 700 nodes shows **24,935% speedup** (8.77ms → 35.0μs)
- **Dense connections**: More edges mean greater savings from avoiding repeated iteration
- **Multiple candidates**: When checking many nodes, the amortized cost of building the set pays off significantly
The speedup grows dramatically with scale - from ~12-62% on tiny graphs (2-3 nodes) to **1600-2100%** on graphs with 100+ nodes, demonstrating the algorithmic improvement's impact on real workloads.
## Edge Case Handling
The `if not sources:` check preserves the original behavior where empty edges means no node has outgoing edges, so the first node is returned without accessing `n["id"]` (avoiding potential KeyError on malformed data).
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.
📄 6,295% (62.95x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
9.89 milliseconds→155 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 6294% speedup (from 9.89ms to 155μs) by eliminating nested iteration through a fundamental algorithmic improvement.
Key Optimization
Original approach: For each node, the code uses
all(e["source"] != n["id"] for e in edges)which requires checking every edge for every node - an O(n×m) operation where n is the number of nodes and m is the number of edges.Optimized approach: Pre-computes a set of all source IDs once (
sources = {e["source"] for e in edges}), then performs O(1) membership checks (n["id"] not in sources). This reduces complexity to O(n+m).Why This Is Faster
Set lookup vs repeated iteration: Python set membership tests are O(1) on average, while iterating through all edges for each node is O(m). With multiple nodes, the original approach repeats this m-times traversal n times.
Single pass through edges: Building the
sourcesset requires one pass through edges (38.7% of optimized runtime), but this one-time cost is amortized across all node checks.Type guard optimization: The
isinstance()check ensures we only use the optimized path for reusable collections, falling back to the original logic for iterators that can't be traversed multiple times.Performance Characteristics
The optimization excels when:
The speedup grows dramatically with scale - from ~12-62% on tiny graphs (2-3 nodes) to 1600-2100% on graphs with 100+ nodes, demonstrating the algorithmic improvement's impact on real workloads.
Edge Case Handling
The
if not sources:check preserves the original behavior where empty edges means no node has outgoing edges, so the first node is returned without accessingn["id"](avoiding potential KeyError on malformed data).✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
📊 Performance Profile
View detailed line-by-line performance analysis
To edit these changes
git checkout codeflash/optimize-find_last_node-ml2f84v0and push.