Home > Software engineering >  Does the execution speed between "if" and "else" differ?
Does the execution speed between "if" and "else" differ?

Time:10-30

I was trying to see the speed difference between == and !=, and it occurred to me that there might be a possibility that the order in an if-else doesn't matter. Purely logically, if you need to test a condition, and have only 2 options, there should not be any difference if you jump to the "if" part or the "else" part.

At least this was my thought process, knowing nothing about how it actually works. This is where you come in.

Here is some code to show what I am trying to choose between:

if (x == 10)
    // do stuff. this will be true 20% of the time
else
    // do frequent stuff
if (x != 10)
    // do frequent stuff 80% of time
else
    // do other stuff 20% of the time

Please help

CodePudding user response:

Modern CPUs are pipelined, so they start executing the next instruction before they are finished with the current. This is great for performance, but there is a problem when the CPU has a branch, like an if statement. The CPU then has to guess which way to go, if it gets it right everything continues at maximum speed, but if it guesses wrong it has to go back and follow the right path, which is quite costly.

You don't have to worry about what exactly affects the CPUs decision making for the guessing as gcc and clang have __builtin_expect which can be used to tell the compiler which branch happens more often.

In your case you could write your code as

if (__builtin_expect(x == 10, 0))
    // do stuff (not expected to happen)
else
    // do frequent stuff (expected)

or

if (__builtin_expect(x != 10, 1))
    // do frequent stuff (expected)
else
    // do stuff (not expected)

You can look at this stackoverflow post for more: What is the advantage of GCC's __builtin_expect in if else statements?

  •  Tags:  
  • c
  • Related