Is bound checking the only runtime cost of Rust?

Bounds checking is the primary one. As for verifying whether it was compiled out, the only way to do that is to view the resulting instructions. And yes, there are ways to help the compiler out. For example, you might have two vectors that you know are the same size, and then write the following code:

for i in array1.len() {
    println!("{} {}", array1[i], array2[i]);
}

Here the compiler can tell that array1 wont go out-of-bounds, but it probably can't for array2, and will insert a bounds check in every iteration. However, you can help the compiler out like this:

assert_eq!(array1.len(), array2.len());
for i in array1.len() {
    println!("{} {}", array1[i], array2[i]);
}

With this code, you still have the assert in the beginning, but you wont have any bounds checks in the loop, and the bounds checks in the loop are a lot more expensive than the assert.


Of course, the other way is to use iterators. Most iterators contain unsafe code that removes the bounds checks, so using them is guaranteed to not have bounds checks.

3 Likes