Skip to content

Reference interferes with optimization #58622

Open
@tspiteri

Description

@tspiteri

(This comes from a Reddit thread.)

In the code below, slow takes double the time fast takes. If print is changed to take a value rather than reference, the difference goes away.

fn print(s: &u64) {
    println!("{}", s);
}
fn fast() {
    let mut s: u64 = 0;
    for x in 0..10000000000 {
        if x % 16 < 4 {
            s += x;
        }
    }
    let s = s;
    print(&s);
}
fn slow() {
    let mut s: u64 = 0;
    for x in 0..10000000000 {
        if x % 16 < 4 {
            s += x;
        }
    }
    print(&s);
}
fn main() {
    if std::env::var("FAST").is_ok() {
        fast();
    } else {
        slow();
    }
}

Timings:

$ rustc -O main.rs
$ time FAST=1 ./main
12499999983750000000

real	0m4.334s
user	0m4.328s
sys	0m0.001s
$ time ./main
12499999983750000000

real	0m8.788s
user	0m8.776s
sys	0m0.002s

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchI-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