How to find common prefix of two byte slices effectively?

#1

Inspired by the code from Knuth Morris Pratt algorithm with C++ and Rust [Solved], I’d like to ask the following question: what is the fastest way to find the first difference between two byte-slices? That is, can the following be made faster?

pub fn prefix(xs: &[u8], ys: &[u8]) -> usize {
    xs.iter().zip(ys)
      .take_while(|(x, y)| x == y)
      .count()
}

Compiler explorer shows that this code generates a loop that does a single byte comparison at a time: https://godbolt.org/z/24JGkA. I expect this could be done quite a bit faster if using simd or just comparing an u64 at a time?

I am surprised that there isn’t a function for this already. There’s memcmp, but it doesn’t reveal the location of mismatch (although it needs to have this info?).

#2

If you use array references instead of slices you will not see a loop at all.

https://play.rust-lang.org/?version=stable&mode=release&edition=2018&gist=66a3456e9151e04cb631d15173d2e37b