Skip to content

Checking reference equality to skip a possibly lengthy computation? #41

@m-ringler

Description

@m-ringler

In the notes for inheritors of System.Object.Equals it says:

The following statements must be true for all implementations of the Equals(Object) method. In the list, x, y, and z represent object references that are not null.

  • x.Equals(x) returns true.

I couldn't find an equivalent statement for IEqualityComparer<T>, but an implementation that returns false for Equals(x, x) would be useless because APIs accepting an IEqualityComparer<T> expect it to implement an equivalence relation. Now, when we have - for example - an IEqualityComparer that implements value equality for a tree-like type by walking the tree, this can take a lot longer than a reference equality check.

Therefore, wouldn't it make sense to include an

if (object.ReferenceEquals(x, y))
{
    return true;
}

in the Equals implementation of EquatableBase<T> and also of EqualityComparerBase<T>?

It wouldn't work if T is a value type, but it also wouldn't do any harm except an unnecessary boxing. On the other hand, there's a lot to gain if T is a reference type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions