Skip to content

Commit ff3222b

Browse files
codeflash-ai[bot]KRRT7
authored andcommitted
⚡️ Speed up function function_has_return_statement by 90%
Here’s a faster rewrite. The original code uses `ast.walk`, which traverses the entire subtree, yielding all nodes. Our target is to determine if any `ast.Return` exists; we can short-circuit the search as soon as we find one, so a custom DFS traversal is much faster. This custom loop avoids constructing and yielding the full list of nodes, and stops immediately once a return is found, improving both speed and memory usage especially for large ASTs. All existing comments preserved (none required updating).
1 parent d64462a commit ff3222b

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

codeflash/discovery/functions_to_optimize.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -541,7 +541,14 @@ def filter_files_optimized(file_path: Path, tests_root: Path, ignore_paths: list
541541

542542

543543
def function_has_return_statement(function_node: FunctionDef | AsyncFunctionDef) -> bool:
544-
return any(isinstance(node, ast.Return) for node in ast.walk(function_node))
544+
# Custom DFS, return True as soon as a Return node is found
545+
stack = [function_node]
546+
while stack:
547+
node = stack.pop()
548+
if isinstance(node, ast.Return):
549+
return True
550+
stack.extend(ast.iter_child_nodes(node))
551+
return False
545552

546553

547554
def function_is_a_property(function_node: FunctionDef | AsyncFunctionDef) -> bool:

0 commit comments

Comments
 (0)