.map view read by index many times
.map(f) read by index in a loop calls f on every read
let xs = [1, 2, 3, 4]
let sq = xs.map(x => x * x)
var t = 0
for i in 0..xs.len:
for j in 0..xs.len:
t += sq[i] + sq[j]
print(t)let xs = [1, 2, 3, 4]
let sq = List(xs.map(x => x * x))
var t = 0
for i in 0..xs.len:
for j in 0..xs.len:
t += sq[i] + sq[j]
print(t)Why
xs.map(f) is a view: sq[i] calls f(xs[i]) each time it is read (R07.2.11), so reading it by index inside a loop pays for f on every read, not once per item. List(xs.map(f)) computes every item once and makes each sq[i] a plain read.
The practice it serves
Code that does more work than it needs to.
Not flagged
A near miss: close to the pattern, but not it.
let xs = [1, 2, 3, 4]
let sq = xs.map(x => x * x)
print(sq.sum())Turn it off
For one block, wrap it in with lint(map_recomputed: allow):. For a project, add map_recomputed = "allow" under [lints] in cp.toml.
Generated from spec/checker-lints/map_recomputed, the same record the linter is built from.