C# byte array comparison

Viewed 26923

I have two byte arrays in C# using .NET 3.0.

What is the "most efficient" way to compare whether the two byte arrays contains the same content for each element?

For example, byte array {0x1, 0x2} is the same as {0x1, 0x2}. But byte array {0x1, 0x2} and byte array {0x2, 0x1} are not the same.

6 Answers

Update for .NET 6.

These days Enumerable.SequenceEqual method is still the best option:

var byteArray1 = new[]{0x01, 0x02};
var byteArray2 = new[]{0x01, 0x02};

bool isEqual = byteArray1.SequenceEqual(byteArray2);

Though, another option is also available out-of-the-box – ReadOnlySpan<T>.SequenceEqual, e.g.:

bool isEqual = new Span<byte>(byteArray1).SequenceEqual(new Span<byte>(byteArray2));

The Span approach used to be faster in the pre-.NET 6 time, but the MS folks drastically optimised implementation of Enumerable.SequenceEqual that's now using ReadOnlySpan<T> under the hood (PR 1, PR 2). See Performance improvements in .NET 6 for more info.

Related