Skip to content

Optimizations not applied when separate variables are used #45126

Closed
@spease

Description

@spease

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.I-slowIssue: Problems and improvements with respect to performance of generated code.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions