天天看點

性能優化-多層嵌套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;
    }
}

           

繼續閱讀