← All lints

chain_walked_twice

L0602Performancewarn

Lazy chain walked twice

a .filter/.map chain kept in a let and walked twice redoes the work

Flagged
let xs = [1, 5, 2, 7]
let big = xs.filter(x => x > 1)
for x in big: print(x)
for x in big: print(x)
Write instead
let xs = [1, 5, 2, 7]
let big = List(xs.filter(x => x > 1))
for x in big: print(x)
for x in big: print(x)

Why

xs.filter(f), .map(f), .take(k) and the rest are lazy views (R07.2): they compute each item as it is walked and store nothing. A view kept in a let and walked twice runs its whole chain twice, calling f again on every item. Copy it once with List(...) when you need it more than once; walk it directly when once is enough.

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.

Near miss
let xs = [1, 5, 2, 7]
let big = xs.filter(x => x > 1)
for x in big: print(x)

Turn it off

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

Generated from spec/checker-lints/chain_walked_twice, the same record the linter is built from.