Basics
This check is disabled by default.
Learn how to enable it via .credo.exs.
This check has a base priority of high and works with any version of Elixir.
Explanation
Replace Enum.sort(...) |> List.first() (or List.last/1) with the
direct extremum function. A full sort is O(N log N); Enum.min/max/ min_by/max_by is O(N).
Why
Sorting a whole list to take a single endpoint is wasted work. The extremum functions visit each element once and never allocate a sorted copy.
How to fix
Pick the replacement from this table based on the original sort and terminal call:
| Before | After |
|---|---|
Enum.sort(xs) | List.first() | Enum.min(xs) |
Enum.sort(xs) | List.last() | Enum.max(xs) |
Enum.sort(xs, :desc) | List.first() | Enum.max(xs) |
Enum.sort_by(xs, f) | List.first() | Enum.min_by(xs, f) |
Enum.sort_by(xs, f, :desc) | List.first() | Enum.max_by(xs, f) |
What NOT to do
Do not "fix" by switching List.first to hd/1 or Enum.at(_, 0) -
that keeps the unnecessary sort. The sort itself is the cost; replace
the whole expression with the extremum function.
Check-Specific Parameters
There are no specific parameters for this check.
General Parameters
Like with all checks, general params can be applied.
Parameters can be configured via the .credo.exs config file.