This is just a simple test of 3 different loops (for, while and do-while).
Link to the blog post about this test.
We're running the 3 different loops through with both post and pre increment.
Running them all 4 times, once with a single iteration, then with 5000, 5001 and 4999 iterations.
Title | 5000 | 5001 | 4999 | Avarage | Difference |
for loop ++var | 0.000014 | 0.000015 | 0.000015 | 0.000015 | 100.00% |
for loop var++ | 0.000015 | 0.000015 | 0.000015 | 0.000015 | 102.16% |
while loop ++var | 0.000016 | 0.000016 | 0.000016 | 0.000016 | 108.65% |
while loop var++ | 0.000016 | 0.000015 | 0.000015 | 0.000015 | 104.32% |
do-while loop ++var | 0.000015 | 0.000015 | 0.000016 | 0.000015 | 104.32% |
do-while loop var++ | 0.000015 | 0.000016 | 0.000016 | 0.000016 | 106.49% |
goto ++var | 0.000016 | 0.000016 | 0.000016 | 0.000016 | 109.19% |
goto var++ | 0.000015 | 0.000015 | 0.000015 | 0.000015 | 102.16% |
The do-while and while loops seems to be faster than the for loops.
<?php
// --- Informative block
$title = "Empty loops";
$teaser = "This is just a simple test of 3 different loops (<em>for</em>, <em>while</em> and <em>do-while</em>).";
$description = "We're running the 3 different loops through with both post and pre increment.<br />Running them all 4 times, once with a single iteration, then with 5000, 5001 and 4999 iterations.";
$conclusion = "The do-while and while loops seems to be faster than the for loops.";
$link = "http://birk-jensen.dk/2010/11/benchmark-class-release-first-test/";
// --- Actual test
if ( isset($runTest) ) {
// -- Initialize the test
require_once(dirname(__FILE__) . "/../Bench.php");
$b = new Bench();
$it = array(1, 5000, 5001, 4999);
$dontSave = true;
$headers = array("5000", "5001", "4999");
foreach ($it as $itValue) {
// For loop ++$i
$b->start("for loop ++var", $itValue, $dontSave);
for ($i = 0; $i < $itValue; ++$i) {
// Nothing
}
$b->end("for loop ++var", $itValue);
// For loop $i++:
$b->start("for loop var++", $itValue, $dontSave);
for ($i = 0; $i < $itValue; $i++) {
// Nothing
}
$b->end("for loop var++", $itValue);
// while ++$i
$b->start("while loop ++var", $itValue, $dontSave);
$i = 0;
while ( ++$i < $itValue) {
// Nothing
}
$b->end("while loop ++var", $itValue);
// While loop $i++:
$b->start("while loop var++", $itValue, $dontSave);
$i = 0;
while ( $i++ < $itValue) {
// Nothing
}
$b->end("while loop var++", $itValue);
// Do while ++$i:
$b->start("do-while loop ++var", $itValue, $dontSave);
$i = 0;
do {
// Nothing
} while (++$i < $itValue);
$b->end("do-while loop ++var", $itValue);
// Do while $i++
$b->start("do-while loop var++", $itValue, $dontSave);
$i = 0;
do {
// Nothing
} while ($i++ < $itValue);
$b->end("do-while loop var++", $itValue);
$b->start("goto ++var", $itValue, $dontSave);
$i = 0;
a:
if (++$i < $itValue) {
goto a;
}
$b->end("goto ++var", $itValue);
$b->start("goto var++", $itValue, $dontSave);
$i = 0;
b:
if ($i++ < $itValue) {
goto b;
}
$b->end("goto var++", $itValue);
$dontSave = false;
}
}