Credence.Rule.NoListAppendInReduce
(credence v0.3.2)
Copy Markdown
Performance rule: Detects acc ++ [expr] as the return value inside
Enum.reduce/3 when the initial accumulator is [].
Appending to a list with ++ is O(n) — it copies the entire left-hand
list on every iteration, compounding to O(n²). The auto-fix rewrites to
prepend with [expr | acc] and wraps the reduce with |> Enum.reverse(),
which is O(n) total.
Bad
Enum.reduce(list, [], fn item, acc ->
acc ++ [item * 2]
end)
list |> Enum.reduce([], fn item, acc ->
acc ++ [process(item)]
end)Good
Enum.reduce(list, [], fn item, acc ->
[item * 2 | acc]
end)
|> Enum.reverse()