Credence.Rule.NoSortThenAt
(credence v0.2.0)
Copy Markdown
Performance rule: Detects sorting an entire list only to retrieve a single
element by index via Enum.at/2.
Sorting is O(n log n), and if you only need one element (e.g. the kth
largest or the median), the full sort is wasteful. For k=1 use Enum.min/1
or Enum.max/1 (O(n)). For small k, consider a partial sort or heap.
Bad
Enum.sort(nums, :desc) |> Enum.at(k - 1)
Enum.at(Enum.sort(nums), 0)Good
Enum.min(nums) # for the smallest
Enum.max(nums) # for the largest
Enum.sort(nums) |> Enum.take(k) # when you need the top-k list