Rust: Reference interferes with optimization

Created on 21 Feb 2019  路  2Comments  路  Source: rust-lang/rust

(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
I-slow T-compiler

Most helpful comment

This sounds somewhat similar to https://medium.com/@robertgrosse/how-copying-an-int-made-my-code-11-times-faster-f76c66312e0f

All 2 comments

This sounds somewhat similar to https://medium.com/@robertgrosse/how-copying-an-int-made-my-code-11-times-faster-f76c66312e0f

Could it also be a similar thing that enables the assert_eq optimization?

Was this page helpful?
0 / 5 - 0 ratings