Home > database >  Optimisation 3 array and foreach
Optimisation 3 array and foreach

Time:09-02

Hi how can i optimize my code ?

$time_start = microtime(true);

$max = 2000;

$vx = [];
for ($i = 0; $i < $max; $i  ) {
    $vx[$i] = $i;
}

$vy = [];
for ($i = 0; $i < $max; $i  ) {
    $vy[$i] = $i;
}

$z = [];
$nb = 0;
foreach ($vx as $kx=>$x) {
    foreach ($vy as $ky=>$y) {
        $z[$x][$y] = cos($x*$x)-sin($y*-2);
        $nb  ;
    }
}

$time_end = microtime(true);

echo ($time_end-$time_start).' microsec to process and calculate '.$nb.' z values';

And after this

$time_start = microtime(true);
$max = 2000;
$vx = [];
$vy = [];
for ($i = 0; $i < $max; $i  ) {
    $vx[$i] = $i;
    $vy[$i] = $i;
}

$z = [];
$nb = 0;
foreach ($vx as $kx=>$x) {
    foreach ($vy as $ky=>$y) {
        $z[$x][$y] = cos($x*$x)-sin($y*-2);
        $nb  ;
    }
}

$time_end = microtime(true);

echo ($time_end-$time_start).' microsec to process and calculate '.$nb.' z values';

CodePudding user response:

The foreach loops are not necessary nor are the 2 arrays you build. It can all be done in 2 for loops like this

$max = 10;
$z = [];
for ($i = 0; $i < $max; $i  ) {
    for ($j = 0; $j < $max; $j  ) {
        $z[$i][$j] = cos($i*$i)-sin($j*-2);
    }
}
print_r($z);

CodePudding user response:

And after this

$time_start = microtime(true);
$max = 2000;
$vx = [];
$vy = [];
for ($i = 0; $i < $max; $i  ) {
    $vx[$i] = $i;
    $vy[$i] = $i;
}

$z = [];
$nb = 0;

for ($i = 0; $i < $max; $i  ) {
    for ($j = 0; $j < $max; $j  ) {
        $z[$i][$j] = cos($i*$i)-sin($j*-2);
    }
}


$time_end = microtime(true);

echo ($time_end-$time_start).' microsec to process and calculate '.$nb.' z values';```

can i optimise the double foreach ?
  • Related