Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

case-statement or if-statement efficiency perspective [duplicate]

Possible Duplicates:
Is "else if" faster than "switch() case"?
What is the relative performance difference of if/else versus switch statement in Java?

I know that case statements can be implemented with jump tables. Does this make them more efficient than if statements?

Is this just micro-optimization that should be avoided?

like image 266
sixtyfootersdude Avatar asked Aug 02 '10 12:08

sixtyfootersdude


2 Answers

I think the main thing is to write the code as clearly as possible. Micro-optimizations like this shouldn't be the focus.

For example, if you have something like this:

if (age == 10) {
  // ...   
} else if (age == 20) {
  // ...   
} else if (age == 30) {
  // ...   
} else if (age == 40) {
  // ...   
}

Then it's clearer to use a switch statement:

switch (age) {
    case 10:
        // ...
        break;
    case 20:
        // ...
        break;
    case 30:
        // ...
        break;
    case 40:
        // ...
        break;
}

Again, I would focus on making the code easiest to read and maintain rather than nano-second level efficiency gains.

like image 137
dcp Avatar answered Sep 22 '22 11:09

dcp


Any compiler will make the jump table if it can verify that the values are reasonably compact. (I doubt if they are in this case, being multiples of 10.)

This is a micro-optimization. Micro-optimization makes sense only if you know that it does. Typically, there are larger "fish to fry" elsewhere, in the form of function calls that could be done without. However, if you have already tuned the daylights out of this code, and your profiling shows that a good fraction (like 10% or more) of time is going into these IF statements (and not to their contents) then it helps. This can happen, for example, in a byte-code interpreter.

Added: Another reason I like to use switch is, even if it doesn't make a jump table - when stepping through the code in a debugger, it goes directly to the proper case, rather than making me step through a lot of false if statements. Makes it easier to debug.

like image 31
Mike Dunlavey Avatar answered Sep 23 '22 11:09

Mike Dunlavey