Credence.Pattern.NoMapUpdateThenFetch (credence v0.4.0)

Copy Markdown

Performance rule: Detects calling Map.update/4 (or Map.update!/3) on a map variable and then immediately reading the same key back with Map.fetch!/2 or Map.get/2.

Map.update/4 traverses the map to apply the new value. Following it with Map.fetch!/2 or Map.get/2 on the same variable performs a second independent traversal. Calculate the new value first, then use Map.put/3 so both the value and the updated map are available without a second lookup.

Bad

map = Map.update(map, key, 1, &(&1 + 1))
val = Map.fetch!(map, key)

Good

val = case Map.fetch(map, key) do
  {:ok, v} -> (&(&1 + 1)).(v)
  :error -> 1
end
map = Map.put(map, key, val)