Advantage of switch over if-else statement

后端 未结 22 2131
梦谈多话
梦谈多话 2020-11-22 11:08

What\'s the best practice for using a switch statement vs using an if statement for 30 unsigned enumerations where about 10 have an ex

22条回答
  •  情歌与酒
    2020-11-22 12:00

    I know its old but

    public class SwitchTest {
    static final int max = 100000;
    
    public static void main(String[] args) {
    
    int counter1 = 0;
    long start1 = 0l;
    long total1 = 0l;
    
    int counter2 = 0;
    long start2 = 0l;
    long total2 = 0l;
    boolean loop = true;
    
    start1 = System.currentTimeMillis();
    while (true) {
      if (counter1 == max) {
        break;
      } else {
        counter1++;
      }
    }
    total1 = System.currentTimeMillis() - start1;
    
    start2 = System.currentTimeMillis();
    while (loop) {
      switch (counter2) {
        case max:
          loop = false;
          break;
        default:
          counter2++;
      }
    }
    total2 = System.currentTimeMillis() - start2;
    
    System.out.println("While if/else: " + total1 + "ms");
    System.out.println("Switch: " + total2 + "ms");
    System.out.println("Max Loops: " + max);
    
    System.exit(0);
    }
    }
    

    Varying the loop count changes a lot:

    While if/else: 5ms Switch: 1ms Max Loops: 100000

    While if/else: 5ms Switch: 3ms Max Loops: 1000000

    While if/else: 5ms Switch: 14ms Max Loops: 10000000

    While if/else: 5ms Switch: 149ms Max Loops: 100000000

    (add more statements if you want)

提交回复
热议问题