Credence.Rule.NoEagerWithIndexInReduce (credence v0.2.0)

Copy Markdown

Performance rule: Detects Enum.with_index/1 passed directly as the enumerable argument to Enum.reduce/3 (or piped into it).

Enum.with_index/1 is eager — it traverses the entire list and allocates a new list of {value, index} tuples before Enum.reduce begins. This doubles memory consumption for large lists.

Bad

Enum.reduce(Enum.with_index(list), acc, fn {val, idx}, acc -> ... end)

list |> Enum.with_index() |> Enum.reduce(acc, fn ...)

Good

# Option 1: Use Stream.with_index for lazy evaluation
list |> Stream.with_index() |> Enum.reduce(acc, fn {val, idx}, acc -> ... end)

# Option 2: Track the index in the accumulator
Enum.reduce(list, {0, acc}, fn val, {idx, acc} -> {idx + 1, ...} end)