This is a problem that pertains to every programmer, and over thousands of lines of code, performance slow downs can really add up based on a programmer's loop preference. Obviously there are situations where one is more suited to the task than the other two, but there are others where a developer may just pick a loop that they are most comfortable using. We will test the performance implications of all three.
Test Environment: Linux, Apache, PHP 5.2.17.
Test Setup: Code constructs listed below. For loops used to have enough iterations to make the script execution time calculatable. Each test was run 3000 times to get the average.
Comparisons
Using a for loop
for($i=0; $i<100000; $i++)
{
//Do Something
}
Using a while loop
$i=0;
while($i<100000)
{
//do something
$i++;
}
Using a do while loop
$i=0;
do
{
//do something
$i++;
} while($i<100000);
| Results | ||
|---|---|---|
| Test | Avg Execution Time | Comparative Graph - (longer is slower, 100% is the fastest time) |
| for loop | 23.44 ms | |
| while loop | 24.65 ms | |
| do while loop | 22.96 ms | |
Discussion: The Do While loops is the fastest (strange) followed by the for loop and the while loop. I actually thought that the for loop would be slower than the while loop given its shortcut format (from my experience, shortcuts in syntax mean longer execution times.)