以下是我寫來測試對於迴圈內的程式,同樣的結果,不同樣的寫法所花費的時間比較

//===============
// 計算執行時間
//===============
function runTime($fn,$params){
    $start = time() + microtime();
    call_user_func ($fn,$params);
    $end = time() + microtime();
    return number_format($end-$start,8);
}
//===============
// if 外提
//===============
function test1($n){
    for($i=0;$i<$n;$i++){
        if(!($i%2)){
            for($j=0;$j<$n;$j++){
                if(!($j%2)){
                    //echo '兩個都是偶數耶';
                }
            }                
        }

    }
}
//===============
// if 沒有外提
//===============
function test2($n){
    for($i=0;$i<$n;$i++){
        for($j=0;$j<$n;$j++){
            if(!($i%2) && !($j%2)){
                //echo '兩個都是偶數耶';
            }
        }
    }
}
echo 'test1: '.runTime('test1',500);
echo 'test2: '.runTime('test2',500);
/*
執行結果:
test1: 0.03964901
test2: 0.10012698
*/

資料參考:大師談Java遊戲設計

從此實驗可見,若迴圈內的 if 判斷式的絛件,不需要用到迴圈內的遞增變數量,那麼就外提吧!

arrow
arrow
    全站熱搜

    低溫烘培 發表在 痞客邦 留言(0) 人氣()