vendredi 9 octobre 2015

Why comparing in IF-statement is really faster than comparing for accessing array element?

The output of both of these codes is identical:

Initialization:

$a=1;
$b=0;
$c=1;

Array method:

$start = microtime( true );
for ($i = 0; $i < 1000000; ++$i) {

    $arr = array('0'=>array('0'=>array('0'=>'zero-zero-zero','1'=>'zero-zero-one'),
                            '1'=>array('0'=>'zero-one-zero', '1'=>'zero-one-one')),
                 '1'=>array('0'=>array('0'=>'one-zero-zero','1'=>'one-zero-one'),
                            '1'=>array('0'=>'one-one-zero','1'=>'one-one-one')));

}

    $total_time = microtime( true ) - $start;
    echo "Total time: ", number_format($total_time, 6), PHP_EOL.'<br>';

IF-statement method:

$start = microtime( true );
for ($i = 0; $i < 1000000; ++$i) {

    if($a==0){
        if($b==0){
            if($c==0){
                $var = 'zero-zero-zero';
            }
            elseif($c==1){
                $var = 'zero-zero-one';
            }
        }
        elseif($b==1){
            if($c==0){
                $var = 'zero-one-zero';
            }
            elseif($c==1){
                $var = 'zero-one-one';
            }
        }
    }
    elseif($a==1){
        if($b==0){
            if($c==0){
                $var = 'one-zero-zero';
            }
            elseif($c==1){
                $var = 'one-zero-one';
            }
        }
        elseif($b==1){
            if($c==0){
                $var = 'one-one-zero';
            }
            elseif($c==1){
                $var = 'one-one-one';
            }
        }
    }
}

    $total_time = microtime( true ) - $start;
    echo "Total time: ", number_format($total_time, 6), PHP_EOL.'<br>';

Output:

/* arry method */ echo $arr[$a][$b][$c]; // output: one-zero-one
/* if method   */ echo $var;              // output: one-zero-one

Since the results are exactly the same, so why, and really why there is much difference in processing time??

/* arry method */ Total time: 15.799611 
/* if method   */ Total time: 1.432304 

Aucun commentaire:

Enregistrer un commentaire