一直认为switch的效率高于if,特别对于条件大于3的时候,以前也貌似看过资料说:switch的查找类似二叉树,if的则是线性。
最近做了一个简单的测试,对有多个条件式的switch和if做比较,发现两者的效率几乎相同,if的效率甚至高于switch;<测试环境sun jdk6.1.13>
40个条件式的测试,测试1000 0000次,if耗时219ms, switch耗时234ms,平均都在4-5k/s;
30个条件式的测试,测试1000 0000次,if耗时188 switch耗时172平均都在5-6kw/s,
20个条件式,测试1000 0000次,if耗时109mswitch耗时125ms,平均在8-9kw/s
总结:
1 经过jdk的改进,目前switch和if的性能上差别微乎其微
2 条件式的多少对于一般应用的整体性能来说,影响也非常小。
3 影响效率的最大因子是条件式的数量,而非if或switch
测试代码
private static void testSitchAndIf(){
int testCount = 10000000;
int flag = 0;
Random random = new Random(testCount);
int[] flags = new int[testCount];
for(int i = 0; i < testCount; i++){
flags[i] = random.nextInt() + 1;
}
// 先统一取一遍值,保证测试都用缓存值
for(int i = 0; i < testCount; i++){
flag = flags[i];
}
long time1 = System.currentTimeMillis();
for(int i = 0; i < testCount; i++){
//flag = random.nextInt() + 1;
flag = flags[i];
if(flag == 1){}
else if(flag == 2){}
else if(flag == 3){}
else if(flag == 4){}
else if(flag == 5){}
else if(flag == 6){}
else if(flag == 7){}
else if(flag == 8){}
else if(flag == 9){}
else if(flag == 10){}
else if(flag == 11){}
else if(flag == 12){}
else if(flag == 13){}
else if(flag == 14){}
else if(flag == 15){}
else if(flag == 16){}
else if(flag == 17){}
else if(flag == 18){}
else if(flag == 19){}
else if(flag == 20){}
else if(flag == 21){}
else if(flag == 22){}
else if(flag == 23){}
else if(flag == 24){}
else if(flag == 25){}
else if(flag == 26){}
else if(flag == 27){}
else if(flag == 28){}
else if(flag == 29){}
else if(flag == 30){}
// else if(flag == 31){}
// else if(flag == 32){}
// else if(flag == 33){}
// else if(flag == 34){}
// else if(flag == 35){}
// else if(flag == 36){}
// else if(flag == 37){}
// else if(flag == 38){}
// else if(flag == 39){}
// else if(flag == 40){}
}
long time2 = System.currentTimeMillis();
for(int i = 0; i < testCount; i++){
flag = flags[i];
switch(flag){
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;
case 10: break;
case 11: break;
case 12: break;
case 13: break;
case 14: break;
case 15: break;
case 16: break;
case 17: break;
case 18: break;
case 19: break;
case 20: break;
case 21: break;
case 22: break;
case 23: break;
case 24: break;
case 25: break;
case 26: break;
case 27: break;
case 28: break;
case 29: break;
case 30: break;
// case 31: break;
// case 32: break;
// case 33: break;
// case 34: break;
// case 35: break;
// case 36: break;
// case 37: break;
// case 38: break;
// case 39: break;
// case 40: break;
// case 41: break;
}
}
long time3 = System.currentTimeMillis();
System.out.println("loop count:" + testCount);
System.out.println("if consume time:" + (time2 - time1) + ",avg:" + testCount / (time2 - time1) * 1000);
System.out.println("switch consume time:" + (time3 - time2) + ",avg:" + testCount / (time3 - time2) * 1000);
}