最佳答案
当在Rust中对数组运行求和循环时,我注意到CAPACITY
>= 240时性能下降很大。CAPACITY
= 239大约快80倍。
Rust是否为“短”数组做了特殊的编译优化?
用rustc -C opt-level=3
编译。
use std::time::Instant;
const CAPACITY: usize = 240;
const IN_LOOPS: usize = 500000;
fn main() {
let mut arr = [0; CAPACITY];
for i in 0..CAPACITY {
arr[i] = i;
}
let mut sum = 0;
let now = Instant::now();
for _ in 0..IN_LOOPS {
let mut s = 0;
for i in 0..arr.len() {
s += arr[i];
}
sum += s;
}
println!("sum:{} time:{:?}", sum, now.elapsed());
}