Increment with foreach() and range() vs for()

Submitted by darraghenright on Wed, 02/13/2013 - 22:28

f1 is slower than f2 by 0%

Full source code as executed.
/* How many times the code under test should run in each function */
define('LOOP',10000000);
 
function f1() {
  for($i=0; $i<LOOP; ++$i) {
    foreach (range(0, 100) as $i) {
      echo $i . PHP_EOL;        
    }
  }
}
function f2() {
  for($i=0; $i<LOOP; ++$i) {
    for ($i = 0; $i <= 100; $i++) {
      echo $i . PHP_EOL;        
    } 
  }
}
$start = microtime(true);
f1();
$stop = microtime(true);
$time1 = $stop - $start;
 
$start = microtime(true);
f2();
$stop = microtime(true);
$time2 = $stop - $start;
 
echo $time1 . "\t";
echo $time2 . "\n";
Test results
comparisontime1time2php_version
No test results (yet)
50%
updown
50%