绝大多数的程序员喜欢使用if判断,但是真的效率高吗?还是其它的,可能只会用if呢!我们今天就具体测一测,用事实说话,测试量100W:

理论上,switch是利用空间换时间。为了避免实验干扰,先行执行了gc()操作,后面提示了对应的内存消耗。

本文采用的是【Java】语言进行测试,后续会有【Python】【C#】

switch效率测试代码:

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);
switch (ch){
case 0:break;
case 1:break;
case 2:break;
case 3:break;
case 4:break;
case 5:break;
case 6:break;
case 7:break;
case 8:break;
case 9:break;
default:break;
}
}
long endMem =r.freeMemory(); // 末尾Memory
long end = System.currentTimeMillis();
System.out.println("switch判断"+count+"次用时:"+(end-start)+"毫秒");
System.out.println("内存消耗: "+String.valueOf((startMem- endMem)/1024)+"KB");
}

100W次swtich判断,消耗时间15ms,消耗内存1331KB

switch-case和if-else的效率比较·必看_java

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

switch-case和if-else的效率比较·必看_垃圾回收_02

结论:

综上实验可得:


1、在100W次循环判断过程中switch判断时间消耗将近是if判断的一半

2、在100W次循环判断过程中switch判断内存消耗比if判断节约33.32%