[英]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:假设我在 C# 中有一个通用方法,它接受两个 T 类型的值:
public void M<T>(T a, T b)
{
...
}
Inside body of M() I wish to compare both input values for equality.在 M() 的内部,我希望比较两个输入值是否相等。 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:
由于我对它们的运行时类型一无所知,除了它们是相同的类型,我可以使用 object.Equals() static 方法来做到这一点,并让它选择最好的方法:
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.我在这里看到的问题是当 T 不是引用类型时对两个值进行不必要的装箱。 I would like to avoid that penalty, because M() is called very frequently.
我想避免这种惩罚,因为 M() 被非常频繁地调用。
My question is: is there a better way to go about this?我的问题是:有没有更好的方法来 go 关于这个? 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.
我显然对一个不涉及太多预先分析 T 的解决方案感兴趣,这将抵消拳击规避带来的收益。
TIA. 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.这在可用时使用
IEquatable<T>
来避免装箱,并处理值类型、引用类型和针对Nullable<T>
的“提升”用法,以避免在几乎所有情况下装箱。
When IEquatable<T>
is not available, it must defer to object.Equals
, so boxing of value-types may occur.当
IEquatable<T>
不可用时,它必须object.Equals
,因此可能会发生值类型的装箱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.