which one will execute faster flag==0 or 0==flag and why?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • unconquerable
    New Member
    • Oct 2010
    • 3

    #1

    which one will execute faster flag==0 or 0==flag and why?

    if of the following will execute faster
    Code:
    if ( flag == 0) 
    {
    }
    or
    Code:
    if ( 0 == flag) 
    {
    }
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    insignificant I would say.
    But I bet if(!flag) is faster still.

    Comment

    • Oralloy
      Recognized Expert Contributor
      • Jun 2010
      • 988

      #3
      It all depends on what assembly code the compiler generates. Essentially, do "0 == flag" and "flag == 0" compile down to the same code, or not?

      Then there are the questions of how the system executes the assembly language level comparison command. Various computers will behave differently, depending. On a PDP-11 or VAX, the entire test is boiled down to one memory instruction which may be 10 or 12 bytes long, depending on the "addressing mode" used for the operands. Who knows if loading an immediate "0" followed by a memory fetch to a stack location is faster than the other way around. Or perhaps it's one simple test instruction, depending on the command set available.

      Lastly ... a really good optimizer will eliminate the whole code sequence, as there is nothing to do as the consequent of the test. In this case, execution time for the "if" statement is exactly zero.

      Cheers! :)
      Oralloy

      Comment

      Working...