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

简介: switch-case和if-else的效率比较·必看(下)

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


微信图片_20220112153131.png


结论:


综上实验可得:


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


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

相关文章
|
4月前
kettle开发篇-switch case
kettle开发篇-switch case
159 0
kettle开发篇-switch case
|
1月前
|
Go
Go 重构:尽量避免使用 else、break 和 continue
Go 重构:尽量避免使用 else、break 和 continue
|
4月前
|
编译器 C语言
learn_C_deep_7 (switch 语句的基本理解、case 的作用、break的作用switch、case 推荐规则)
learn_C_deep_7 (switch 语句的基本理解、case 的作用、break的作用switch、case 推荐规则)
|
测试技术 API 数据库
如何设计自动化测试Case?
测试工作的本质是尽可能以更高的效率保障交付产出物的质量满足甚至超出预期,这是所有测试工作的最终目标。
如何设计自动化测试Case?
switch case 执行
switch case 执行
115 0
|
Java
switch case 语句有如下规则
switch case 语句有如下规则
161 0
封装一个RxCondition,告别if else和switch case
封装一个RxCondition,告别if else和switch case
117 0
|
算法 编译器 C语言
if else 和 switch的效率
switch在判断分支时,没有判断所有的可能性,而是用一个静态表来解决这个问题,所以速度要比if-else快。 但是,switch对较复杂的表达式进行判断,所以当我们需要判断一些简单数值时,用switch较好。
3357 0
|
存储 开发工具
CASE 工具有哪些
<h2 style="color:rgb(18,18,20); font-weight:normal; letter-spacing:-1px; margin:0.2em 0.2em 0.2em 0px; font-size:1.7em; line-height:1.5em; padding:0px; position:relative; left:0px; font-family:Ver
3683 0
switch……case语句面试题
switch……case语句面试题
106 0