-4

For example, you have the loop:

$i=0;
while($i<5) {
    $x[$i] = $a[$i] + $b[$i];
    $y[$i] = $x[$i] / $c[$i];
    $i++;
}

Does this calculate faster than:

$i=0;
while($i<5) {
    $x[$i] = $a[$i] + $b[$i];
    $i++;
}

$i=0;
while($i<5) {
    $y[$i] = $x[$i] / $c[$i];
    $i++;
}

Or are they the same? I have absolutely no idea how exactly code is compiled or executes.

Thanks for the answers. I'm very new to programming so wasn't aware that it was possible to test the efficiency of code.

Sam Driver
  • 92
  • 1
  • 1
  • 14

3 Answers3

1

You can measure the time spent by your self and figure out the answer...

example, borrowed from Tracking the script execution time in PHP

$rustart = getrusage();

// script start
$i=0;
while($i<5) {
    $x[$i] = $a[$i] + $b[$i];
    $i++;
}


// Script end
function rutime($ru, $rus, $index) {
    return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
     -  ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}

$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
    " ms for its computations\n";
echo "It spent " . rutime($ru, $rustart, "stime") .
    " ms in system calls\n";
Simonluca Landi
  • 931
  • 8
  • 21
0

The second piece of code will definitly take more time. You do exactly the same operations in both pieces of code, the only two differences being that you double the loop itself and the incrementations on $i.

This code :

while ($i < 5) {
    ++$i;
}

will consume the same amount of time wherever you put it. If you write that code twice, it will take twice the time.

That's why putting both assignments in the same loop will give you the better performance.

Sarkouille
  • 1,275
  • 9
  • 16
0

There is a very simple way to find out, just feed the code to http://3v4l.org and take a look at the output!

Example 1

Example 1

Note Generally speaking, however, it depends on what you are doing in the loops, and what you want to optimize for:

  • performance of the code
  • readability of the code

If you want to measure the performance yourself, take a look at benchmarking tools, such as

or profilers, such as

or application performance services, such as

localheinz
  • 9,179
  • 2
  • 33
  • 44