if效率测试代码:
public static void main(String[] args) { /** * switch与if效率测试·测试次数为100W */ int count=1000000; Random ra = new Random(); Runtime r = Runtime.getRuntime(); r.gc();//计算内存前先垃圾回收一次 long start = System.currentTimeMillis(); long startMem = r.freeMemory(); // 开始Memory for (int i = 0; i < count; i++) { int ch=ra.nextInt(10); if(ch==0){ }else if(ch==1){ }else if(ch==2){ }else if(ch==3){ }else if(ch==4){ }else if(ch==5){ }else if(ch==6){ }else if(ch==7){ }else if(ch==8){ }else if(ch==9){ }else if(ch==10){ } } long endMem =r.freeMemory(); // 末尾Memory long end = System.currentTimeMillis(); System.out.println("if判断"+count+"次用时:"+(end-start)+"毫秒"); System.out.println("内存消耗: "+String.valueOf((startMem- endMem)/1024)+"KB"); }
100W次if判断,消耗时间31ms,消耗内存1996KB
结论:
综上实验可得:
1、在100W次循环判断过程中switch判断时间消耗将近是if判断的一半
2、在100W次循环判断过程中switch判断内存消耗比if判断节约33.32%