Saturday, October 10, 2009

Pre vs Post Increment in PHP

Earlier on I was browsing Google Code, and I chanced upon JSpeed - a javascript optimizer. I saw that they actually change post increments to pre-increments. I wondered why and thought I could ask this on Stack Overflow.

One theory came up to be "preincrement (++i) adds one to the value of i, then returns i; in contrast, i++ returns i then adds one to it, which in theory results in the creation of a temporary variable storing the value of i before the increment operation was applied". -- http://physical-thought.blogspot.com/2008/11/pre-vs-post-increment-speed-test.html

So I thought, what about PHP?

I went on to test it on PHP with a FOR loop and I have the following code:
<?php

$time_start = microtime_float();

for($i = 0; $i<10000000;$i++){

}

$time_end = microtime_float();
$loadedin = (float)($time_end - $time_start);
echo $loadedin.' s
';

$time_start = microtime_float();

for($i = 0; $i<10000000;++$i){

}

$time_end = microtime_float();
$loadedin = (float)($time_end - $time_start);
echo $loadedin.' s
';

function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}


?>


Amazingly, pre-increment is much faster than post-increment in PHP. Look at the results:
 Pre-inc (seconds)Post-inc (seconds)
Mean0.686950.74147
Min0.6859259605410.740597963333
Max0.688167810440.743010044098


Thus I conclude that pre-increment is useful in for loops than post-increment. It is much faster through the iterations.

1 comment:

Dragonmantank said...

In all honesty though, you probably will run into very few instances where you are incrementing over such a large iteration.

Even assuming a large dataset, it is unrealistic that you will need to count 10 million records. You're more likely to run out of memory than be impacted by a single millisecond of operation time.