Credence.Rule.NoListAppendInLoop
(credence v0.2.0)
Copy Markdown
Performance rule: Detects the use of ++ inside looping constructs
(Enum.reduce, for comprehensions) and inside recursive functions.
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.
Bad ā inside Enum.reduce
Enum.reduce(list, [], fn item, acc ->
acc ++ [item * 2]
end)Bad ā inside a recursive function
defp slide([next | rest], window, current, max) do
new_window = window ++ [next]
slide(rest, new_window, current, max)
endGood
Enum.reduce(list, [], fn item, acc ->
[item * 2 | acc]
end)
|> Enum.reverse()