⚡️ Speed up function find_last_node by 17,331%#279
Open
codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
Open
⚡️ Speed up function find_last_node by 17,331%#279codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
find_last_node by 17,331%#279codeflash-ai[bot] wants to merge 1 commit intooptimizefrom
Conversation
The optimized code achieves a **174x speedup** (17,331% improvement) by eliminating redundant edge scanning through a fundamental algorithmic optimization.
## Key Optimization: Set-Based Lookup
**Original approach** (O(|nodes| × |edges|)):
- For each node, scans *all* edges to check if `n["id"]` matches any `e["source"]`
- With 1000 nodes and 1000 edges, this performs ~1,000,000 comparisons
- Line profiler shows 444ms spent in the nested iteration
**Optimized approach** (O(|nodes| + |edges|)):
- **Pre-computes** a set of all source IDs: `sources = {e["source"] for e in edges}` (single pass)
- Uses set membership testing: `n["id"] not in sources` (O(1) lookup per node)
- Line profiler shows only 571μs total (296μs for set creation, 275μs for node iteration)
## Why This Works in Python
Set membership testing (`in` operator) uses hash table lookups with O(1) average time complexity. The original code's nested `all()` generator with edge iteration forces repeated linear scans. By converting edges to a set once, we trade a small upfront cost (296μs) for massive savings on the node iteration phase.
## Performance Impact by Test Case
The optimization excels when:
- **Large edge counts**: `test_large_linear_chain_1000_nodes` improves from 17.9ms → 46μs (389x faster)
- **Dense graphs**: `test_large_graph_with_many_edges_single_sink` improves from 9.24ms → 32.8μs (281x faster)
- **Late sinks**: `test_large_linear_chain_find_middle_sink` improves from 4.49ms → 24μs (187x faster)
Even small graphs benefit (40-90% faster) due to Python's efficient set implementation. The only minor regression is `test_no_nodes_returns_none` (24% slower) where the set creation overhead exceeds the benefit for empty graphs—an acceptable trade-off given the dramatic improvements in real-world scenarios.
## Impact Summary
This optimization transforms the function from quadratic to linear complexity, making it viable for production workflows with large graph structures. The 174x average speedup means operations that took ~64ms now complete in ~369μs, enabling real-time graph analysis in data pipelines and workflow engines.
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.
📄 17,331% (173.31x) speedup for
find_last_nodeinsrc/algorithms/graph.py⏱️ Runtime :
64.2 milliseconds→369 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 174x speedup (17,331% improvement) by eliminating redundant edge scanning through a fundamental algorithmic optimization.
Key Optimization: Set-Based Lookup
Original approach (O(|nodes| × |edges|)):
n["id"]matches anye["source"]Optimized approach (O(|nodes| + |edges|)):
sources = {e["source"] for e in edges}(single pass)n["id"] not in sources(O(1) lookup per node)Why This Works in Python
Set membership testing (
inoperator) uses hash table lookups with O(1) average time complexity. The original code's nestedall()generator with edge iteration forces repeated linear scans. By converting edges to a set once, we trade a small upfront cost (296μs) for massive savings on the node iteration phase.Performance Impact by Test Case
The optimization excels when:
test_large_linear_chain_1000_nodesimproves from 17.9ms → 46μs (389x faster)test_large_graph_with_many_edges_single_sinkimproves from 9.24ms → 32.8μs (281x faster)test_large_linear_chain_find_middle_sinkimproves from 4.49ms → 24μs (187x faster)Even small graphs benefit (40-90% faster) due to Python's efficient set implementation. The only minor regression is
test_no_nodes_returns_none(24% slower) where the set creation overhead exceeds the benefit for empty graphs—an acceptable trade-off given the dramatic improvements in real-world scenarios.Impact Summary
This optimization transforms the function from quadratic to linear complexity, making it viable for production workflows with large graph structures. The 174x average speedup means operations that took ~64ms now complete in ~369μs, enabling real-time graph analysis in data pipelines and workflow engines.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-find_last_node-mlfs7qfsand push.