Duplicate byte array equivalence check methods

Hi. I removed my own “byte array equivalence” code recently when I noticed ServiceStack already had code to do what I need.

That said, I discovered there seems to be two methods checking byte array equivalence, one seems to shortcut on difference (which would be “better/faster” I guess), except the other uses aggressive inlining (suggesting to me that it is a high performance situation and so would benefit from early exit logic.

I have pasted both ServiceStack methods below, as far as I can see they ultimately achieve the same thing but am unsure if this is
a) an intentional copy given the slightly different logic and inlining or
b) some low hanging fruit that could be tided/unified.

    public static bool AreEqual(this byte[] b1, byte[] b2)
        if (b1 == b2) return true;
        if (b1 == null || b2 == null) return false;
        if (b1.Length != b2.Length) return false;

        for (var i = 0; i < b1.Length; i++)
            if (b1[i] != b2[i]) return false;

        return true;
    public static bool EquivalentTo(this byte[] bytes, byte[] other)
        if (bytes == null || other == null)
            return bytes == other;

        if (bytes.Length != other.Length)
            return false;

        var compare = 0;
        for (var i = 0; i < other.Length; i++)
            compare |= other[i] ^ bytes[i];

        return compare == 0;

They’re different in that EquivalentTo() is a constant time byte[] comparison which is what you’d use for comparing cryptographic hashes to mitigate against timing attacks.

For all other use cases you should use the short-circuiting AreEqual(), I agree that EquivalentTo() should be better named to distinguish the difference so I’ve added a comment in this commit.

1 Like

Thanks… I’d never heard of this concept, doing some reading now and the purpose is clear (and fascinating).