Why does a loop over an array of 240+ elements run 10 times slower in Rust?
Hello, colleagues. I'm learning Rust and encountered what seems to me inexplicable behavior. I wrote a simple benchmark: summing array elements in a `for` loop. For arrays up to 239 elements, everything is blazing fast (less than 1 μs). As soon as the size reaches 240, the execution time jumps sharply to 10–15 μs. Further size increases give a smooth increase in time, but this first 10x jump puzzled me.
Here's the code I'm testing:
```rust
use std::time::Instant;
fn sum_array(arr: &[i32]) -> i32 {
let mut sum = 0;
for &x in arr {
sum += x;
}
sum
}
fn main() {
let size = 240;
let arr: Vec = (0..size).collect();
let start = Instant::now();
let _ = sum_array(&arr);
println!("{:?}", start.elapsed());
}
```
I
No answers yet.
Log in to leave an answer