简体   繁体   English

比较两个相等值的最有效方法是什么?

[英]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.

相关问题 哪个是比较两位数最高效的方法? - Which is the most performant way to compare two digits? 比较两个数组是否相同的最快方法是什么? - What's the fastest way to compare two arrays for equality? 比较这两个列表最有效的方法是什么? - What's the most efficient way to compare these two lists? 在 C# 中比较两个 DateTime 的相等性的最佳方法是什么……但只能达到一定的精度? - What's the best way to compare the equality of two DateTime's in C#… but only to a certain precision? 比较两个字符串的最有效方法是什么? - what is the most efficient way to compare two strings? 将巨大的项目列表作为参数传递给 SQL 服务器的最高效方法是什么? - What's the most performant way to pass a giant list of items as a parameter to SQL Server? 什么是表现最好的,为什么? - What will be the most performant and Why? 比较两个词典的最佳方法 <T> 为了平等 - Best way to compare two Dictionary<T> for equality 比较/排序两个阵列中的项目的最有效方法是什么? - What is the most efficient way to compare/sort items from two arrays? 比较 XML 文件是否相等的最佳方法是什么? - What is the best way to compare XML files for equality?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM