If and else, were should I put the more likely part?
Asked Answered
R

11

10

I was wondering if there is a big performance difference in languages, whether you should put the more likely to be executed code in the if or in the else clause. Here is an example:

// x is a random number, or some key code from the user
if(!somespecific_keycode)
   do the general stuff
else
   do specific stuff

and the other solution

if(somespecific_keycode)
   do the specific stuff
else
   do general stuff
Rummage answered 1/8, 2012 at 16:37 Comment(2)
That depends heavily on the compiler, the compiler version, the optimizing options you chose and sometimes just the weather. But in 99.999% of all real-world cases I can think of you will most probably notice no difference.Climax
There will be a performance difference... on the scale of NANOSECONDS! That won't be noticeable to anyone except superman.Kirstinkirstyn
W
10

Prefer to put them in the order that makes the code clearer, which is usually having the more likely to be executed first.

Whirly answered 1/8, 2012 at 16:41 Comment(1)
Fully supporting this answer. Good organizations with elaborate coding conventions would include this into rulesTumbling
C
8

As others said: in terms of performance you should best rely on your compiler and your hardware (branch prediction, speculative execution) to do the right thing.

In case you are really concerned that these two don't help you enough, GCC provides a builtin (__builtin_expect) with which you can explicitly indicate the expected outcome of a branch.

In terms of code readability, I personally like the more likely case to be on top.

Cuthbert answered 1/8, 2012 at 16:42 Comment(3)
I voted up this answer, and it would be better if you explained how to use __builtin_expect and gave an example.Dewittdewlap
that only counts, when the compiler knows which one is more probable, when it comes to user input, the programmer knows best whats the most likely option the user will chooseRummage
An example for __builtin_expect() can be found in the documentation I linked to.Cuthbert
M
4

Unless you experience a performance problem, don't worry about it.

If you do experience a performance problem, try switching them around and measure which variant is faster, if any of them.

Mesocratic answered 1/8, 2012 at 16:39 Comment(0)
R
2

The common rule is to put more likely case first, it's considered to be more readable.

Revengeful answered 1/8, 2012 at 16:40 Comment(0)
F
1

branch prediction will cause one of those to be more likely and it will cause a performance difference if inside a loop. But mostly you can ignore that if you are not thinking at assembler level.

Fiske answered 1/8, 2012 at 16:39 Comment(0)
C
1

This isn't necessarily a performance concern, but I usually go from specific to general to prevent cases like this:

int i = 15;

if(i % 3 == 0)
   System.out.println("fizz");
else if(i % 5 == 0)
   System.out.println("buzz");
else if(i % 3 == 0 && i % 5 == 0)
   System.out.println("fizzbuzz");   

Here the above code will never say 'fizzbuzz', because 15 matches both the i % 3 == 0 and i % 5 == 0 conditions. If you re-order into something more specific:

int i = 15;

if(i % 3 == 0 && i % 5 == 0)
   System.out.println("fizzbuzz");
else if(i % 3 == 0)
   System.out.println("fizz");
else if(i % 5 == 0)
   System.out.println("buzz");  

Now the above code will reach "fizzbuzz" before getting stopped by the more general conditions

Chagrin answered 1/8, 2012 at 16:43 Comment(0)
C
1

All answers have valid points. Here is an additional one:

  • Avoid double negations: if not this, then that, else something tends to be confusing for the reader. Hence for the example given, I would favor:

    if (somespecific_keycode) {
        do_the_specific_stuff();
    } else {
        do_general_stuff();
    }
    
Crewelwork answered 17/7, 2017 at 10:58 Comment(0)
N
0

It mostly doesn't make a difference but sometimes it is easier to read and debug if your ifs are checking if something is true or equal and the else handles when that isn't the case.

Novikoff answered 1/8, 2012 at 16:41 Comment(0)
E
0

As the others have said, it's not going to make a huge difference unless you are using this many many times (in a loop for example). In that case, put the most likely condition first as it will have the earliest opportunity to break out of the condition checking.

It become more apparent when you start having many 'else if's .

Estelaestele answered 1/8, 2012 at 16:42 Comment(0)
M
0

Any difference that may arise is more related to the context than inherently with if-else constructions. So the best you can do here is develop your own tests to detect any difference.

Unless you are optimizing an already finished system or software, what I'd recommend you is avoid premature optimizations. Probably you've already heard they are evil.

Mayce answered 1/8, 2012 at 16:42 Comment(0)
L
0

AFAIK with modern optimizing C compilers there is no direct relation between how you organize your if or loop and actual branching instructions in generated code. Moreover different CPUs have different branch prediction algorithms.

Therefore:

  • Don't optimize until you see bad performance related to this code

  • If you do optimize, measure and compare different versions

  • Use realistic data of varied characteristics for performance measurement

  • Look at assembly code generated by your compiler in both cases.

Lancastrian answered 1/8, 2012 at 16:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.