Does assert help reduce boundschecking

For example if I'm creating a tuple of 4 elements from a vector, would writing assert_eq!(v.len() == 4) beforehand help reduce boundschecking every time I index the v?

Yes, it could. Verify with https://rust.godbolt.org (remember to add -O to flags!)

Another trick is to use:

let slice = &arr[0..4];

and then the optimizer will see that this slice must be at least 4 elements long.

Passing -Copt-level=3 is actually preferred, as -O is equivalent to -Copt-level=2. -Ctarget-cpu=native can help optimizations as well, though it has some bugs.

Absolutely. A quick example: https://rust.godbolt.org/z/vzxnz3saE

Adding the assert makes the generated code smaller and faster.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.