case-statement or if-statement efficiency perspective

sixtyfootersdude picture sixtyfootersdude · Aug 2, 2010 · Viewed 16.3k times · Source

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?

Answer

dcp picture dcp · Aug 2, 2010

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.