Open
Description
(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