Credence.Pattern.NoRepeatedEnumTraversal
(credence v0.4.4)
Copy Markdown
Performance rule: warns when the same variable is traversed multiple
times using different Enum functions.
Repeated traversal of the same collection with separate Enum calls
(e.g. Enum.max/1, Enum.min/1, and Enum.count/1 on the same
list) allocates and iterates the data structure multiple times.
Consider combining traversals into a single Enum.reduce/3 or
caching intermediate results.
Bad
def stats(list) do
max = Enum.max(list)
min = Enum.min(list)
count = Enum.count(list)
{max, min, count}
end
if Enum.member?(list, 10) and Enum.member?(list, 20) do
Enum.count(list)
endGood
def stats(list) do
Enum.reduce(list, fn el, {max, min, count} ->
{max(max, el), min(min, el), count + 1}
end)
end
set = MapSet.new(list)
if MapSet.member?(set, 10) and MapSet.member?(set, 20) do
MapSet.size(set)
end