Is if(var == true) faster than if(var != false)?

后端 未结 10 961
礼貌的吻别
礼貌的吻别 2020-12-18 18:25

Pretty simple question. I know it would probably be a tiny optimization, but eventually you\'ll use enough if statements for it to matter.

EDIT: Thank you to those o

相关标签:
10条回答
  • Makes no measurable difference at all, no matter how many iterations you use in your program.

    (Use if (var) instead; you don't need the visual clutter of the comparisons.)

    0 讨论(0)
  • 2020-12-18 19:04

    It will make no difference at all. Using reflector you can see that the code:

    private static void testVar(bool var)
    {
        if (var == true)
        {
            Console.WriteLine("test");
        }
    
        if (var != false)
        {
            Console.WriteLine("test");
        }
    
        if (var)
        {
            Console.WriteLine("test");
        }
    }
    

    creates the IL:

    .method private hidebysig static void testVar(bool var) cil managed
    {
      .maxstack 8
      L_0000: ldarg.0 
      L_0001: brfalse.s L_000d
      L_0003: ldstr "test"
      L_0008: call void [mscorlib]System.Console::WriteLine(string)
      L_000d: ldarg.0 
      L_000e: brfalse.s L_001a
      L_0010: ldstr "test"
      L_0015: call void [mscorlib]System.Console::WriteLine(string)
      L_001a: ldarg.0 
      L_001b: brfalse.s L_0027
      L_001d: ldstr "test"
      L_0022: call void [mscorlib]System.Console::WriteLine(string)
      L_0027: ret 
    }
    

    So the compiler (in .Net 3.5) translates them all to the ldarg.0, brfalse.s instruction set.

    0 讨论(0)
  • 2020-12-18 19:04

    It makes no difference, and the compiler is free to interchange them at will.

    For example, you could write

    if (!predicate)
        statement1;
    else
        statement2;
    

    and the compiler is free to emit code equivalent to

    if (predicate)
        statement2;
    else
        statement1;
    

    or vice-versa.

    0 讨论(0)
  • 2020-12-18 19:08

    It will make absolutely zero difference, because the compiler would almost certainly compile the two statements to the same binary code.

    The (pseudo) assembly will either be:

    test reg1, reg2
    br.true somewhere
    ; code for false case
    
    somewhere:
    ; code for true case
    

    or

    test reg1, reg2
    br.false somewhere
    ; code for true case
    
    somewhere:
    ; code for false case
    

    Which of those the compiler chooses will not depend on whether you write == true or != false. Rather, it's an optimisation the compiler will make based on the size of the true and false case code and perhaps some other factors.

    As an aside, the Linux kernel code actually does try to optimise these branches using LIKELY and UNLIKELY macros for its if conditions, so I guess it is possible to manually control it.

    0 讨论(0)
提交回复
热议问题