Array.Equals

"I wish .NET can compare contents of an Array." - Annoymous Array Comparer

Currently, when you compare two arrays with the = operator, we are really using the System.Object's = operator, which only compares the instances. (i.e. this uses reference equality, so it will only be true if both arrays points to the exact same instance) 

Well until we add this feature request in the framework itself, I've provided a temporary solution for you:

public static bool ArrayEquals<T>(T[] a, T[] b)

{

if (a.Length != b.Length)

return false;

for (int i = 0; i < a.Length; i++)

{

if (!a[i].Equals(b[i]))

return false;

}

return true;

}

Again, my solution is not perfect, because if you are comparing value types, I am boxing the value type before calling System.Object::Equal as you can see here:

IL_0026: box !!T
IL_002b: constrained. !!T
IL_0031: callvirt instance bool [mscorlib]System.Object::Equals(object)

My office neighbour Brian Grunkemeyer have the following perf suggestions:

1) Add a generic constraint to this method

public static bool ArrayEquals<T>(T[] a, T[] b) where T: IEquatable<T>

This will help our performance, but limits the method to only take types that implement IEquatable<T>. This may be too restrictive for some though.

2) Use EqualityComparer<T>.Default's Equal method instead of calling Equals on the types themselves.

    public static bool ArrayEquals<T>(T[] a, T[] b)

    {

        if (a.Length != b.Length)

            return false;

        EqualityComparer<T> comparer = EqualityComparer<T>.Default;

        for (int i = 0; i < a.Length; i++)

        {

            if (!comparer.Equals(a[i], b[i]))

                return false;

        }

        return true;

    }

Without measuring the perf of these on long arrays, my guess is that for value types #1 has the best perf, followed by #2 and then the original implementation.

What do you think?