Java代码质量的优化点
1.switch 和 if/else 的性能比较
直接上代码:
public class SwitchCompIfElseTest { @Test public void switchCompIfElseTest() { long startTimeSwitch = System.nanoTime(); for (int i = 0; i < 1; i++) { switchTest(i); } long timeSwitch = System.currentTimeMillis() - startTimeSwitch; System.out.println("timeSwitch=" + timeSwitch); long startTimeIfElse = System.currentTimeMillis(); for (int i = 0; i < 1; i++) { ifElseTest(i); } long timeIfElse = System.nanoTime() - startTimeIfElse; System.out.println("timeIfElse=" + timeIfElse); } private void switchTest(int i) { switch (i) { case 0: System.out.println("i=" + i); break; case 1: System.out.println("i=" + i); break; case 2: System.out.println("i=" + i); break; case 3: System.out.println("i=" + i); break; case 4: System.out.println("i=" + i); break; case 5: System.out.println("i=" + i); break; case 6: System.out.println("i=" + i); break; case 7: System.out.println("i=" + i); break; case 8: System.out.println("i=" + i); break; case 9: System.out.println("i=" + i); break; default: System.out.println("i=" + i); break; } } private void ifElseTest(int i) { if (i == 0) { System.out.println("i=" + i); } else if (i == 1) { System.out.println("i=" + i); } else if (i == 2) { System.out.println("i=" + i); } else if (i == 3) { System.out.println("i=" + i); } else if (i == 4) { System.out.println("i=" + i); } else if (i == 5) { System.out.println("i=" + i); } else if (i == 6) { System.out.println("i=" + i); } else if (i == 7) { System.out.println("i=" + i); } else if (i == 8) { System.out.println("i=" + i); } else if (i == 9) { System.out.println("i=" + i); } else { System.out.println("i=" + i); } } }
测试结果: