Credence.Rule.NoListAppendInLoop (credence v0.3.0)

Copy Markdown

Performance rule: Detects the use of ++ inside looping constructs that cannot be auto-fixed.

Appending to a list with ++ is O(n) because it must copy the entire left-hand list. Inside a loop or recursion this compounds to O(n²). Prefer prepending with [item | acc] and calling Enum.reverse/1 after the loop completes.

Note: simple acc ++ [expr] patterns inside Enum.reduce with [] initial are handled by ListAppendInReduce, and direct acc ++ [expr] in recursive tail calls (with a matching base case) are handled by ListAppendInRecursion. This rule covers the remaining unfixable cases: for comprehensions, indirect appends in recursion, and complex reduce patterns.

Bad — inside a for comprehension

for item <- list do
  acc = []
  acc ++ [item]
end

Bad — indirect append in recursion (assigned to variable first)

defp slide([next | rest], window, current, max) do
  new_window = window ++ [next]
  slide(rest, new_window, current, max)
end

Good

Enum.reduce(list, [], fn item, acc ->
  [item * 2 | acc]
end)
|> Enum.reverse()