简体   繁体   中英

What's the most performant way to compare two values for equality?

Say I have a generic method in C# that accepts two values of type T:

public void M<T>(T a, T b)
{
    ...
}

Inside body of M() I wish to compare both input values for equality. Since I don't know anything about their run-time types except that they are the same type, I could do this using the object.Equals() static method and let it choose the best way:

public void M<T>(T a, T b)
{
    if (object.Equals(a, b))
    {
        ...
    }
    else
    {
        ...
    }
}

The problem I see here is needless boxing of the two values when T isn't a reference type. I would like to avoid that penalty, because M() is called very frequently.

My question is: is there a better way to go about this? I'm obviously interested in a solution that wouldn't involve too much analysis of T up front, which would offset gains from boxing evasion.

TIA.

if(EqualityComparer<T>.Default.Equals(a,b))
{...}

this uses IEquatable<T> when available to avoid boxing, and handles value-types, reference-types, and "lifted" usage against Nullable<T> to avoid boxing in almost all scenarios.

When IEquatable<T> is not available, it must defer to object.Equals , so boxing of value-types may occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM