← All lints

wide_array

L0606Performancewarn

Wide Int array with narrow values

a large [n]Int whose every write fits a narrower range

Flagged
var a: [1000000]Int = 0
a[3] = 1
a[7] = 2
print(a[3] + a[7])
Write instead
var a: [1000000]0..=2 = 0
a[3] = 1
a[7] = 2
print(a[3] + a[7])

Why

An Int is 8 bytes. When every value written into a large array is a constant in a small range, declaring that range as the element type ([n]0..=2) stores each one in the fewest bytes the range allows (R03.1.8), so the array takes a fraction of the memory and more of it fits in cache. A write outside the range then traps instead of storing a value you did not expect.

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
var a: [1000]Int = 0
a[3] = 1
a[7] = 2
print(a[3] + a[7])

Turn it off

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

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