How to find common prefix of two byte slices effectively?


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 {
      .take_while(|(x, y)| x == y)

Compiler explorer shows that this code generates a loop that does a single byte comparison at a time: 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?).


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