← All lints

sort_for_extreme

L0572Idiomswarn

Sorting to read the smallest or largest

xs.sorted()[0] / xs.sorted().last! sorts a copy for one element: xs.min() / xs.max()

Flagged
let xs = [3, 1, 4]
print(xs.sorted()[0], xs.sorted().last!)
Write instead
let xs = [3, 1, 4]
print(xs.min(), xs.max())

Why

xs.sorted()[0] copies and sorts the whole list, O(nlog⁡n)O(n \log n) and an allocation, to read one element. xs.min() (and xs.max() for .last!) reads it in one O(n)O(n) pass with no copy, and traps on an empty list just as [0] does; keys carry over as xs.min(by: f). When the sorted list is used again, keep it in a let and the lint stays quiet.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.seq: reductions.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let xs = [3, 1, 4]
let s = xs.sorted()
print(s[0], s.last!, s[1], xs.sorted()[1])

Turn it off

For one block, wrap it in with lint(sort_for_extreme: allow):. For a project, add sort_for_extreme = "allow" under [lints] in cp.toml.

Generated from spec/lints/sort_for_extreme, the same record the linter is built from.