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) | |
|---|---|---|
| Mean | 0.68695 | 0.74147 |
| Min | 0.685925960541 | 0.740597963333 |
| Max | 0.68816781044 | 0.743010044098 |
Thus I conclude that pre-increment is useful in for loops than post-increment. It is much faster through the iterations.


1 programmer comments:
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.
Post a Comment