Skip to content

Commit a39edd2

Browse files
⚡️ Speed up method AssertCleanup._transform_assert_line by 34% in PR #26 (clean_concolic_tests)
To optimize the `AssertCleanup` class, we can improve the `_transform_assert_line` method by reducing the use of regular expressions, and replacing them with more efficient string operations where possible. Where regular expressions are still necessary, we compile them once and reuse them. Here's the refactored code. ### Explanation of Changes. 1. **Regex Compilation in `__init__`**: Compiled the regular expressions in the `__init__` method to avoid recompiling them every time `_transform_assert_line` is called, improving speed. 2. **String Operations for Trailing Characters**: Replaced `re.sub` used to strip trailing commas or semicolons with simpler string operations, improving efficiency. These improvements help in optimizing the running speed of the program while maintaining the same functionality.
1 parent b79db77 commit a39edd2

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

codeflash/code_utils/code_replacer.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -354,21 +354,23 @@ def transform_asserts(self, code: str) -> str:
354354
return "\n".join(result_lines)
355355

356356
def _transform_assert_line(self, line: str) -> Optional[str]:
357-
indent = line[: len(line) - len(line.lstrip())]
357+
indent_len = len(line) - len(line.lstrip())
358+
indent = line[:indent_len]
358359

359-
assert_match = re.match(r"\s*assert\s+(.*?)(?:\s*==\s*.*)?$", line)
360+
assert_match = self.assert_pattern.match(line)
360361
if assert_match:
361362
expression = assert_match.group(1).strip()
362363
if expression.startswith("not "):
363364
return f"{indent}{expression}"
364365

365-
expression = re.sub(r"[,;]\s*$", "", expression)
366+
# Removing trailing commas or semicolons without using regex
367+
if expression and expression[-1] in ",;":
368+
expression = expression[:-1]
366369
return f"{indent}{expression}"
367370

368-
unittest_match = re.match(r"(\s*)self\.assert([A-Za-z]+)\((.*)\)$", line)
371+
unittest_match = self.unittest_pattern.match(line)
369372
if unittest_match:
370373
indent, assert_method, args = unittest_match.groups()
371-
372374
if args:
373375
arg_parts = self._split_top_level_args(args)
374376
if arg_parts and arg_parts[0]:
@@ -399,6 +401,10 @@ def _split_top_level_args(self, args_str: str) -> list[str]:
399401

400402
return result
401403

404+
def __init__(self):
405+
self.assert_pattern = re.compile(r"\s*assert\s+(.*?)(?:\s*==\s*.*)?$")
406+
self.unittest_pattern = re.compile(r"(\s*)self\.assert([A-Za-z]+)\((.*)\)$")
407+
402408

403409
def clean_concolic_tests(test_suite_code: str) -> str:
404410
try:

0 commit comments

Comments
 (0)