300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > switch-case和if-else的效率比较·必看

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

时间:2022-05-14 11:11:13

相关推荐

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

绝大多数的程序员喜欢使用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(); // 开始Memoryfor (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(); // 末尾Memorylong end = System.currentTimeMillis();System.out.println("switch判断"+count+"次用时:"+(end-start)+"毫秒");System.out.println("内存消耗: "+String.valueOf((startMem- endMem)/1024)+"KB");}

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

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(); // 开始Memoryfor (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(); // 末尾Memorylong 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%

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。