Skip to content

Commit 93d383e

Browse files
⚡️ Speed up function get_diff_lines_count by 16% in PR #284 (saga4/fix_duplication_suggestion_issue)
Here's a faster version of your program. The main bottleneck is the list comprehension calling a nested function for every line, leading to relatively high overhead. Avoiding the inner function, only iterating once, and not building an intermediate list (since we only need the count) can significantly improve performance. You do **not** need to build the list of lines; simply scan and count qualifying lines in a single pass. Optimized version. **Changes made:** - Inlined the `is_diff_line` logic for better performance (function call overhead avoided). - Used a running integer (`count`) instead of a list, so memory use and processing are reduced. - Avoided creating an unnecessary list and removed the nested function. **This is as fast and memory-efficient as this logic gets in idiomatic Python.**
1 parent 620ca38 commit 93d383e

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

codeflash/code_utils/formatter.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,12 @@ def get_diff_output_by_black(filepath: str, unformatted_content: str) -> Optiona
2424

2525

2626
def get_diff_lines_count(diff_output: str) -> int:
27-
lines = diff_output.split("\n")
28-
29-
def is_diff_line(line: str) -> bool:
30-
return line.startswith(("+", "-")) and not line.startswith(("+++", "---"))
31-
32-
diff_lines = [line for line in lines if is_diff_line(line)]
33-
return len(diff_lines)
27+
# Count only the diff lines as per is_diff_line logic, but avoid unnecessary function call and list allocation.
28+
count = 0
29+
for line in diff_output.split("\n"):
30+
if line and line[0] in "+-" and not (line.startswith("+++") or line.startswith("---")):
31+
count += 1
32+
return count
3433

3534

3635
def is_safe_to_format(filepath: str, content: str, max_diff_lines: int = 100) -> bool:

0 commit comments

Comments
 (0)