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?