Credence.Pattern.NoStringConcatInLoopComplex (credence v0.4.0)

Copy Markdown

Performance rule: Detects string concatenation with <> inside complex looping constructs that cannot be safely auto-fixed.

This rule detects <> inside:

  • Enum.reduce_while — the accumulated value drives the halting logic
  • for comprehensions with reduce — complex multi-generator syntax
  • Recursive functions — too varied to generalise
  • Enum.reduce with block bodies or non-empty initial accumulators

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

Bad

Enum.reduce_while(chars, "", fn char, prefix ->
  candidate = prefix <> char
  if valid?(candidate), do: {:cont, candidate}, else: {:halt, prefix}
end)

for char <- chars, reduce: "" do
  acc -> acc <> char
end

def build("", acc), do: acc
def build(<<char::utf8, rest::binary>>, acc) do
  build(rest, acc <> <<char::utf8>>)
end

Good

graphemes
|> Enum.reduce([], fn char, acc -> [char | acc] end)
|> Enum.reverse()
|> IO.iodata_to_binary()

Enum.join(graphemes)