0

I made the following performance test for PHP. I am trying to profile the time it takes to increment a variable in four ways, in a array $time: [{++$x}, {$x++}, {$x += 1}, {$x = $x + 1}]

$time = [0, 0, 0, 0];
for($i = 0; $i < 50; ++$i){
    $k = 0;
    $t = microtime(true);
    $x = 0;
    for($j = 0; $j < 100; ++$j)
        ++$x;
    $time[$k++] += microtime(true) - $t;

    $t = microtime(true);
    $x = 0;
    for($j = 0; $j < 100; ++$j)
    $x++;
    $time[$k++] += microtime(true) - $t;

    $t = microtime(true);
    $x = 0;
    for($j = 0; $j < 100; ++$j)
        $x += 1;
    $time[$k++] += microtime(true) - $t;

    $t = microtime(true);
    $x = 0;
    for($j = 0; $j < 100; ++$j)
        $x = $x + 1;
    $time[$k++] += microtime(true) - $t;
}
echo '++$x: ', $time[0] * 1000, 'ms<br />';
echo '$x++: ', $time[1] * 1000, 'ms<br />';
echo '$x += 1: ', $time[2] * 1000, 'ms<br />';
echo '$x = $x + 1: ', $time[3] * 1000, 'ms<br />';

I got as average of 10 runs: 0.28ms for ++$x and $x++, 0.26ms for $x += 1 and 0.24ms for $x = $x + 1

I thought, ++$x and $x++ are faster, but here they are slower. Did I made an error in my script or is this really the normal performance of PHP 5.5.9?

Chubas
  • 17,823
  • 4
  • 48
  • 48
pixunil
  • 641
  • 1
  • 5
  • 19
  • "I thought, ++$x and $x++ are faster, but their are slower" well that is the problem... You thought wrong. http://3v4l.org/MQRZK :) Although **sometimes the other is faster, but we are talking about a level here that you should not even care – PeeHaa Aug 14 '14 at 18:00
  • Check for example [`$i++`](http://3v4l.org/rucfY/vld#tabs) vs [`$i += 1`](http://3v4l.org/PkKXt/vld#tabs) – PeeHaa Aug 14 '14 at 18:16
  • In all honesty you are also only seeing half of the story. You should be considering the increase in time versus the potential memory usage. In the examples you have posted the memory usage will be quite low but not so clear cut in real world examples. I would also suggest that your tests are too short. – Peter Aug 30 '14 at 22:04

0 Answers0