Closed
Description
I noticed a case from this thread where the optimizations applied by the compiler are determined by the presence or absence of intermediate variables
fn main() {
let a = [100u8; 1024];
let b = [200u8; 1024];
let c = a.iter().zip(b.iter()).map(|(ai, bi)| ai.saturating_add(*bi)).sum::<u8>();
println!("c: {:?}", c);
}
fn main() {
let c = [100u8; 1024].iter().zip([200u8; 1024].iter()).map(|(ai, bi)| ai.saturating_add(*bi)).sum::<u8>();
println!("c: {:?}", c);
}
Looking at the assembly in the first case, it's clearly generating the two arrays separately.
movl $100, %esi
movl $1024, %edx
callq memset@PLT
leaq 1096(%rsp), %rdi
movl $200, %esi
movl $1024, %edx
callq memset@PLT
In the second case, it does not appear to generate the arrays.
This is a little bit surprising to me and seems a bit undesirable since this means that making code more readable by storing intermediate operations in variables could lead to optimizations not being applied.