PHP & Web Development :: PHP Performance + Benchmarking :: Loop comparisons

PHP Loop comparisons: for, while, and do while loops

BulletThis 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 4.3.11 with PHP loaded using FastCGI. Zend Optimizer 2.5.7 installed. What's Zend Optimizer?

Test Setup: Code constructs listed below.

Refresh the page to execute a new trial!

Comparisons
Bulletfor loop
  • Execution time: 15.60 ms
  • Average: 23.84 ms over 1107 trials
Bulletwhile loop
  • Execution time: 11.16 ms
  • Average: 25.45 ms over 1107 trials
Bulletdo while loop
  • Execution time: 12.69 ms
  • Average: 21.24 ms over 1106 trials
Results
Test Avg Execution Time Comparative Graph - (longer is slower, 100% is the fastest time)
for loop 23.84 ms Performance Graph 112%
while loop 25.45 ms Performance Graph 120%
do while loop 21.24 ms Performance Graph 100%

Discussion: Writing this after only 70 trials, the results may be too close to call. It appears as though 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.)