Checking equality for two byte arrays

You need to add a return value somewhere. This should work:

public bool Equality(byte[] a1, byte[] b1)
{
   int i;
   if (a1.Length == b1.Length)
   {
      i = 0;
      while (i < a1.Length && (a1[i]==b1[i])) //Earlier it was a1[i]!=b1[i]
      {
          i++;
      }
      if (i == a1.Length)
      {
          return true;
      }
   }

   return false;
}

But this is much simpler:

return a1.SequenceEqual(b1);

Alternatively, you could use IStructuralEquatable from .NET 4:

return ((IStructuralEquatable)a1).Equals(b1, StructuralComparisons.StructuralEqualityComparer)

If performance is a concern, I'd recommend rewriting your code to use the Binary class, which is specifically optimized for this kind of use case:

public bool Equality(Binary a1, Binary b1)
{
    return a1.Equals(b1);
}

A quick benchmark on my machine gives the following stats:

Method                   Min         Max         Avg
binary equal:          0.868       3.076       0.933    (best)
for loop:              2.636      10.004       3.065
sequence equal:        8.940      30.124      10.258
structure equal:     155.644     381.052     170.693

Download this LINQPad file to run the benchmark yourself.


I'd recommend some short-circuiting to make things a bit simpler, and use of object.ReferenceEquals to short-circuit for cases when the arrays are the same reference (a1 = b1):

public bool Equality(byte[] a1, byte[] b1)
{
    // If not same length, done
    if (a1.Length != b1.Length)
    {
        return false;
    }

    // If they are the same object, done
    if (object.ReferenceEquals(a1,b1))
    {
        return true;
    }

    // Loop all values and compare
    for (int i = 0; i < a1.Length; i++)
    {
        if (a1[i] != b1[i])
        {
            return false;
        }
    }

    // If we got here, equal
    return true;
}

This should work:

public bool Equality(byte[] a1, byte[] b1)
{
   if(a1 == null || b1 == null)
       return false;
   int length = a1.Length;
   if(b1.Length != length)
      return false;
   while(length >0) {
       length--;
       if(a1[length] != b1[length])
          return false;           
   }
   return true;        
}

To check equality you can just write:

var areEqual =  a1.SequenceEqual(b1);

Tags:

C#