Skip to content

Commit d652567

Browse files
⚡️ Speed up method CfoVisitor._is_codeflash_output_target by 76% in PR #358 (fix-test-reporting)
Here is an optimized rewrite of your program with a focus on improving performance in the `_is_codeflash_output_target` method. These changes focus on avoiding unnecessary generator creation, reducing function calls, and using faster data structures and comparison strategies. **Key optimizations:** - Use `type(...) is ...` instead of `isinstance()` for frequently called type checks for speed. - Unroll the `any(...)` generator over `target.elts` into an explicit for loop to reduce function call and overhead in the hot path. - Avoid recursive generator creation where possible; use explicit returns. - Avoid `isinstance(..., (a, b))` for hot paths (for small type hierarchies and known types); it's slightly faster to compare types directly. These micro-optimizations especially benefit scenarios with large ASTs or heavy tuple/list unpackings. The function's logic and return value are identical to your original version.
1 parent dd44def commit d652567

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

codeflash/code_utils/edit_generated_tests.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,25 @@ def __init__(self, source_code: str) -> None:
5454
self.source_lines = source_code.splitlines()
5555
self.results: list[int] = [] # map actual line number to line number in ast
5656

57-
def _is_codeflash_output_target(self, target: Union[ast.expr, list]) -> bool: # type: ignore[type-arg]
57+
def _is_codeflash_output_target(self, target: Union[ast.expr, list]) -> bool:
5858
"""Check if the assignment target is the variable 'codeflash_output'."""
59-
if isinstance(target, ast.Name):
59+
t_type = type(target)
60+
if t_type is ast.Name:
6061
return target.id == "codeflash_output"
61-
if isinstance(target, (ast.Tuple, ast.List)):
62+
if t_type is ast.Tuple or t_type is ast.List:
6263
# Handle tuple/list unpacking: a, codeflash_output, b = values
63-
return any(self._is_codeflash_output_target(elt) for elt in target.elts)
64-
if isinstance(target, (ast.Subscript, ast.Attribute)):
64+
# Flatten elts (avoid generator, avoid recursion if not necessary):
65+
elts = target.elts
66+
for elt in elts:
67+
if type(elt) is ast.Name:
68+
if elt.id == "codeflash_output":
69+
return True
70+
elif type(elt) is ast.Tuple or type(elt) is ast.List:
71+
# Recursively check nested tuples/lists, but avoid generator
72+
if self._is_codeflash_output_target(elt):
73+
return True
74+
return False
75+
if t_type is ast.Subscript or t_type is ast.Attribute:
6576
# Not a simple variable assignment
6677
return False
6778
return False

0 commit comments

Comments
 (0)