Credence.Rule.NoSortForTopK
(credence v0.2.0)
Copy Markdown
Detects inefficient patterns where a full sort is performed only to retrieve a small number of elements (top-k).
Flagged patterns
| Pattern | Suggested replacement |
|---|
| `Enum.sort/1 | > Enum.take(1)` | Enum.max/1 — O(n) |
| `Enum.sort/1 | > Enum.take(k)` | Enum.reduce/3 (track top k) |
| `Enum.sort/1 | > hd/1` | Enum.max/1 |
| `Enum.sort/1 | > Enum.at(0)` | Enum.min/1 |
| `Enum.sort/1 | > Enum.at(1)` | Enum.reduce/3 (top two) |
| Enum.sort/1 |> Enum.reverse/1 |> … | Same as above (reverse skipped)|
Sorting an entire collection is O(n log n). When only the first or last few elements are needed, a single-pass O(n) approach is both faster and clearer in intent.
Severity
:warning