Credence.Pattern.NoStringConcatInLoop (credence v0.4.2)

Copy Markdown

Performance rule: Detects string concatenation with <> inside Enum.reduce calls with an empty string initial accumulator that can be automatically fixed.

Each <> concatenation copies the entire accumulated binary, making character-by-character string building O(n²). This is the string equivalent of list ++ [element].

The following patterns are automatically fixed:

  • Enum.reduce(list, "", fn elem, acc -> acc <> elem end) → Enum.join(list)
  • Enum.reduce(list, "", fn elem, acc -> acc <> expr end) where expr doesn't reference acc → Enum.map_join(list, fn elem -> expr end)

Bad

Enum.reduce(graphemes, "", fn char, acc ->
  acc <> char
end)

Enum.reduce(graphemes, "", fn char, acc ->
  acc <> String.upcase(char)
end)

Good

Enum.join(graphemes)

Enum.map_join(graphemes, fn char -> String.upcase(char) end)