How to “zip” two slices efficiently

Update: In current rust, itertools::ZipSlices does not codegen well enough anymore, probably due to the removal of a null check elimination llvm pass. (It's too late to edit the original post.)

The indexed loop is still the way to go, making sure to slice to equal length, so that the loop bound and slice bounds check coincide (and are then elided).

fn iterate_slices_counted_2<T>(xs: &[T], ys: &[T]) {
    let len = cmp::min(xs.len(), ys.len());
    let xs = &xs[..len];
    let ys = &ys[..len];
    for i in 0..len {
        let x = &xs[i];
        let y = &ys[i];
        /* do something with `x` and `y` */
    }
}
2 Likes