From e8d3714dc6824787ac1c54aad46e1f0673732770 Mon Sep 17 00:00:00 2001 From: Saurabh Misra Date: Mon, 16 Dec 2024 13:58:32 -0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=20=E2=9A=A1=EF=B8=8F=20Speed=20up?= =?UTF-8?q?=20function=20`find=5Flast=5Fnode`=20by=2029,891%=20(#5261)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ⚡️ Speed up function `find_last_node` by 29,891% Certainly! We can optimize the existing code by minimizing the checks inside the loop and improving the lookup operations. Here's an optimized version of the program. ### Explanation. 1. **Set for Fast Lookup**: We first create a set of all source IDs from the edges. This is efficient because checking for membership in a set is on average O(1) time complexity. 2. **Iterate Through Nodes**: We loop through each node and check if its ID is not in the set of source IDs. If a node's ID is not found in the set, it means this node has no outgoing edges and is the "last node". This approach ensures we only iterate over the edges once to create the set and then do a fast lookup for each node, improving the overall efficiency. Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com> --- src/backend/base/langflow/graph/graph/utils.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/backend/base/langflow/graph/graph/utils.py b/src/backend/base/langflow/graph/graph/utils.py index bce39317c..b0c3a746b 100644 --- a/src/backend/base/langflow/graph/graph/utils.py +++ b/src/backend/base/langflow/graph/graph/utils.py @@ -24,7 +24,11 @@ def find_start_component_id(vertices): def find_last_node(nodes, edges): """This function receives a flow and returns the last node.""" - return next((n for n in nodes if all(e["source"] != n["id"] for e in edges)), None) + source_ids = {edge["source"] for edge in edges} + for node in nodes: + if node["id"] not in source_ids: + return node + return None def add_parent_node_id(nodes, parent_node_id) -> None: