Faster Way of Comparing Generic Sets The following extension method is the limiting factor in the performance of an application I am developing, according to Visual Studio 2012 Performance Analysis profiler.

Is there a faster way to compare two collections for set equality?

public static bool SetEqual&lt;T&gt;(this IEnumerable&lt;T&gt; source, IEnumerable&lt;T&gt; other, IEqualityComparer&lt;T&gt; comparer = null)
{
    if (source == null) {
        throw new ArgumentNullException("source");
    }

    if (other == null) {
        throw new ArgumentNullException("other");
    }

    ICollection&lt;T&gt; sourceCollection = source as ICollection&lt;T&gt; ?? source.ToArray();
    ICollection&lt;T&gt; otherCollection = other as ICollection&lt;T&gt; ?? other.ToArray();

    if (sourceCollection.Count != otherCollection.Count) {
        return false;
    }

    if (sourceCollection.Except(otherCollection, comparer).Any()) {
        return false;
    }

    if (otherCollection.Except(sourceCollection, comparer).Any()) {
        return false;
    }

    return true;
}
It seems you are iterating the sets a lot with the Except method and possibly the ToArray.

Consider iterating the sets at most once:

public static bool SetEqual&lt;T&gt;(this IEnumerable&lt;T&gt; source, IEnumerable&lt;T&gt; other, IEqualityComparer&lt;T&gt; comparer = null)
{
    if (source == null)
        throw new ArgumentNullException("source");

    if (other == null)
        throw new ArgumentNullException("other");

    if (source is ICollection &amp;&amp;
        other is ICollection &amp;&amp;
        ((ICollection)source).Count != ((ICollection)other).Count)
        return false;

    HashSet&lt;T&gt; set;
    if (comparer == null)
        set = new HashSet&lt;T&gt;(source);
    else
        set = new HashSet&lt;T&gt;(source, comparer);

    return set.SetEquals(other);
}


Source IEnumerable implementation.