.NET 3.5/C#:if()==和!=之间是否存在性能差异?

Chr*_*isP 2 .net c#

当使用if()语句时,从性能角度来看,使用==或!=会更好

if(object==null)
Run Code Online (Sandbox Code Playgroud)

要么

if(object!=null)
Run Code Online (Sandbox Code Playgroud)

在if()序列中,成功概率最高的陈述应该是第一个吗?

Mar*_*ell 23

我非常怀疑你是否注意到任何有形的差异; 并非最不重要的,有brtruebrfalseIL运营商...

如果您遇到性能问题,请使用分析器,查看实际问题; 这不是它......它是不成熟的优化.

  • 说得好.鉴于没有任何重大的性能差异,最重要的问题应该是代码清晰度. (2认同)

Jas*_*ans 11

我刚刚在.NET Reflector中分析了以下代码:

public static void Main(string[] args)
{
    object obj2 = null;
    if (obj2 == null)
    {
        Console.WriteLine("Is null");
    }
    if (obj2 != null)
    {
        Console.WriteLine("Is not null");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是由此产生的IL:

.method public hidebysig static void Main(string[] args) cil managed
{
    .custom instance void [mscorlib]System.STAThreadAttribute::.ctor()
    .maxstack 1
    .locals init (
        [0] object obj2)
    L_0000: ldnull 
    L_0001: stloc.0 
    L_0002: ldloc.0 
    L_0003: brtrue.s L_000f
    L_0005: ldstr "Is null"
    L_000a: call void [mscorlib]System.Console::WriteLine(string)
    L_000f: ldloc.0 
    L_0010: brfalse.s L_001c
    L_0012: ldstr "Is not null"
    L_0017: call void [mscorlib]System.Console::WriteLine(string)
    L_001c: ret 
}
Run Code Online (Sandbox Code Playgroud)

从上面看,似乎对if()检查你使用的性能没有任何影响.但是,您可以这样看待它 - 尝试使用最有可能发生的if()检查.因此,如果对象在if检查点很少变为null,则使用if(object!= null).+


Spe*_*ort 10

你不应该在乎.

如果你关注效率,你应该用低级语言写作.不是.Net.