首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >性能优化-多层嵌套for循环如何优化

性能优化-多层嵌套for循环如何优化

作者头像
cwl_java
发布2019-11-29 00:35:26
3.4K0
发布2019-11-29 00:35:26
举报
文章被收录于专栏:cwl_Javacwl_Java
代码示例
package com.cwl.po;

/**
 * @program: cwl-performance-optimization
 * @description: 测试for循环-嵌套循环
 * @author: ChenWenLong
 * @create: 2019-11-22 11:27
 **/
public class TestNestedLoop {

    // 当需要嵌套循环时 外层循环越小 性能越好
    // 例如 10*100*1000 与 1000*100*10 相互比较
    public static void main(String[] args) {
        // 测试最终结果发现当嵌套循环越大 两者相差性能比越大
        System.out.println(testOutSide());
        System.out.println(testInSide());
    }


    /**
     * 功能描述:
     * 〈测试内层循环逐步增大〉
     *
     * @params : []
     * @return : long
     * @author : cwl
     * @date : 2019/11/22 11:36
     */
    private static long testInSide() {
        long begin = System.currentTimeMillis();
        int d = 0;
        for(int a=0;a<1000;a++){
            for(int b=0;b<10000;b++){
                for (int c=0;c<100000;c++){
                    d = a+b+c;
                }
            }
        }
        long end = System.currentTimeMillis();
        System.out.println(d);
        return end - begin;

    }

    /**
     * 功能描述:
     * 〈测试内层循环逐步减小〉
     *
     * @params : []
     * @return : long
     * @author : cwl
     * @date : 2019/11/22 11:37
     */
    private static long testOutSide() {
        long begin = System.currentTimeMillis();
        int d = 0;
        for(int a=0;a<100000;a++){
            for(int b=0;b<10000;b++){
                for (int c=0;c<1000;c++){
                    d = a+b+c;
                }
            }
        }
        long end = System.currentTimeMillis();
        System.out.println(d);
        return end - begin;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-11-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档