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.
精彩评论