【问题标题】:What is better in practice, using ==/!= or is operator? [closed]在实践中,使用 ==/!= 或 is 运算符哪个更好? [关闭]
【发布时间】:2021-02-15 12:46:23
【问题描述】:

在检查变量是否为真、假、空等时,使用传统逻辑运算符(如==!=)与 C# 中的is 运算符进行检查是否存在性能差异?除了任何潜在优化之外,还有什么理由反对使用is,而==!= 可以使用?

is 运算符在具有布尔值和空值的实例中的工作方式似乎相同,但我很好奇任何可能的缺点,例如性能或没有充分记录的最佳实践,以防止使用 is 代替 ==!= 一直没找到,故提示提问。

例如:

if (myObject == false)
{
  ...
}

if (myObject is false)
{
  ...
}

【问题讨论】:

  • 你做了哪些测试/基准测试来确定is there a performance difference in doing a check
  • is 运算符可读性较差,因为程序员必须弄清楚它在这个特定表达式中的可能含义。
  • 查看生成的 IL 可能会让您了解不同之处。
  • @RufusL 为什么你认为他们对 IL 操作性能的了解会比他们对 C# 操作的了解更多?
  • @RufusL 当然,如果您对 IL 有深入的了解,而对 C# 的理解却差强人意,那么这是一种很好的方法,而且很容易实现。但大多数人不在那个位置。

标签: c# .net performance operators


【解决方案1】:

看起来这两个比较在这个比较两个布尔值的特定示例中生成了相同的 IL。

using System;
public class C {
    public bool Foo(bool input) {
        return input == false;
    }
    
    public bool Bar(bool input) {
        return input is false;
    }
}

生成的 IL:

.method public hidebysig 
    instance bool Foo (
        bool input
    ) cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 5 (0x5)
    .maxstack 8

    IL_0000: ldarg.1
    IL_0001: ldc.i4.0
    IL_0002: ceq
    IL_0004: ret
} // end of method C::Foo

.method public hidebysig 
    instance bool Bar (
        bool input
    ) cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 5 (0x5)
    .maxstack 8

    IL_0000: ldarg.1
    IL_0001: ldc.i4.0
    IL_0002: ceq
    IL_0004: ret
} // end of method C::Bar

因此,如果生成的代码相同,我认为这两个操作之间不会有任何性能差异。

【讨论】:

    猜你喜欢
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 2011-01-05
    • 2010-11-24
    • 2013-08-14
    • 1970-01-01
    相关资源
    最近更新 更多