XO0910: a value over 8 words copied into a closure or an Option
Reported by xo vet --cost, which builds the program and reads what the compiler did. A closure captures by value: making it copies each captured value into its environment and shares every heap field of it (Str, Bytes, List, Map, handles), even when the body reads one field. In a loop, Some(x) of a collection’s element copies the whole element out of the collection and shares its heap fields again. Over 8 words (a cache line) that is a cost the source does not show. Bind the fields the closure reads and capture those; return an index or the one field the caller needs instead of the element.
Example
struct Big {
a: Int, b: Int, c: Int, d: Int, e: Int
f: Int, g: Int, h: Int, i: Int
}
fn adder(big: Big) -> fn(Int) -> Int {
fn(k: Int) -> Int { big.a + k }
}Fix
struct Big {
a: Int, b: Int, c: Int, d: Int, e: Int
f: Int, g: Int, h: Int, i: Int
}
fn adder(big: Big) -> fn(Int) -> Int {
let a = big.a
fn(k: Int) -> Int { a + k }
}Run xo explain XO0910 for this text in a terminal, or see
section 10.6 of the specification.