在实践中,使用 ==/!= 或 is 运算符哪个更好?
What is better in practice, using ==/!= or is operator?
当检查变量是否为 true、false、null 等时,使用 ==
、!=
与 [=14= 等传统逻辑运算符进行检查是否存在性能差异] C# 中的运算符?在任何 潜在 优化之外,是否有任何理由反对使用 is
,其中 ==
和 !=
可以?
is
运算符在布尔值和空值的情况下似乎工作相同,但我很好奇任何可能的缺点,如性能或没有很好记录的最佳实践反对在中使用 is
==
, !=
的地方我没能找到,所以提出了这个问题。
例如:
if (myObject == false)
{
...
}
对比
if (myObject is false)
{
...
}
看起来这两个比较在这个比较两个布尔值的特定示例中生成相同的 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
因此,如果生成的代码相同,我认为这两个操作之间不会有任何性能差异。
当检查变量是否为 true、false、null 等时,使用 ==
、!=
与 [=14= 等传统逻辑运算符进行检查是否存在性能差异] C# 中的运算符?在任何 潜在 优化之外,是否有任何理由反对使用 is
,其中 ==
和 !=
可以?
is
运算符在布尔值和空值的情况下似乎工作相同,但我很好奇任何可能的缺点,如性能或没有很好记录的最佳实践反对在中使用 is
==
, !=
的地方我没能找到,所以提出了这个问题。
例如:
if (myObject == false)
{
...
}
对比
if (myObject is false)
{
...
}
看起来这两个比较在这个比较两个布尔值的特定示例中生成相同的 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
因此,如果生成的代码相同,我认为这两个操作之间不会有任何性能差异。