我是靠谱客的博主 迷人鞋垫,最近开发中收集的这篇文章主要介绍性能优化-多层嵌套for循环如何优化,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

代码示例
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;
    }
}

最后

以上就是迷人鞋垫为你收集整理的性能优化-多层嵌套for循环如何优化的全部内容,希望文章能够帮你解决性能优化-多层嵌套for循环如何优化所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部