JHnet
JHnet

Reputation: 471

Is there a difference in performance when swapping if/else condition?

Is there a difference in performance between

if(array[i] == -1){
    doThis();
}
else {
    doThat();
}

and

if(array[i] != -1){
    doThat();
}
else {
    doThis();
}

when I already now that there is only one element (or in general few elements) with the value -1 ?

Upvotes: 2

Views: 152

Answers (4)

abligh
abligh

Reputation: 25119

That will depend entirely on how your compiler chooses to optimise it. You have no guarantee as to which is faster. If you really need to give hints to the compiler, look at the unlikely macro in the Linux kernel which are defined thus:

#define likely(x)      __builtin_expect(!!(x), 1)
#define unlikely(x)    __builtin_expect(!!(x), 0)

Which means you can use

if (likely(something)) { ... }

or

if (unlikely(something)) { ... }

Details here: http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

Moral: write your code for readability, and not how you think the compiler will optimise it, as you are likely to be wrong.

Upvotes: 7

Ansh David
Ansh David

Reputation: 672

That would depend on which condition is encountered first. As such there is not such a big diffrence.

-----> If You have to test a lot of statements, rather than using nested if-else a switch statement would be faster.

Upvotes: 0

mikera
mikera

Reputation: 106351

Performance is always implementation dependent. If it is sufficiently important to you, then you need to benchmark it in your environment.

Having said that: there is probably no difference, because modern compilers are likely to turn both versions into equally efficient machine code.

One thing that might cause a difference is if the different code order changes the compiler's branch prediction heuristics. This can occasionally make a noticeable difference.

Upvotes: 5

webuster
webuster

Reputation: 2510

The compiler wouldn't know about your actual data, so it will produce roughly the same low-level code.

However, given that if-statements generate assembly branches and jumps, your code may run a little faster in your second version because if your value is not -1 then your code will run the very next instruction. Whereas in your first version the code would need to jump to a new instruction address, which may be costly, especially when you deal with a large number of values (say millions).

Upvotes: 5

Related Questions