sixtyfootersdude sixtyfootersdude - 1 year ago 49
Java Question

case-statement or if-statement efficiency perspective


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?

dcp dcp
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download