admin管理员组文章数量:1794759
switch
绝大多数的程序员喜欢使用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%
本文标签: switch
版权声明:本文标题:switch 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1692797709a205735.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论