Skip to content

Compiler fails to recognize that println! does not mutate the value #86510

Description

@fee1-dead

Consider the following two functions:

fn copy() {
    for a in 0..=1000 {
        for b in 0..=1000 {
            for c in 0..=1000 {
                if a * a + b * b == c * c && a + b + c == 1000 {
                    let (a2, b2, c2) = (a, b, c);
                    println!("a:{} b:{} c:{}", a2, b2, c2);
                }
            }
        }
    }
}

fn no_copy() {
    for a in 0..=1000 {
        for b in 0..=1000 {
            for c in 0..=1000 {
                if a * a + b * b == c * c && a + b + c == 1000 {
                    println!("a:{} b:{} c:{}", a, b, c);
                }
            }
        }
    }
}

I would expect these functions to be the same when compiling with optimizations turned on, but they are not.

Currently on nightly copy is faster than no_copy. I speculate it is because println! acts like a black box for whether a, b and c will be mutated or not.

Godbolt

Playground to see the time difference

@rustbot label T-compiler I-slow C-enhancement

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.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions