For VS While in PHP

Today I was coding a new PHP script, when I asked myself “should I use for or while?”…

It’s a question I thought I should know the answer to after I spent a very long time researching 50+ PHP optimisation tips.

One I hadn’t mastered was whether the for() function was faster than while() function, as both can be used for most types of looping.

So what do we know about for and while?

  • John’s PHP Digest says that for is faster than while
  • Cosmin Budinschi’s blog says that while is faster than for
  • bruesoft’s PHP Benchmarking says that while is faster than for
  • php.lt’s PHP benchmark tests has many loop tests

I’m sure there’s many more, but there’s nothing new, and nothing conclusive…

A quick search for “for vs while php” landed me on Mgccl’s blog, where last year, he had tested and benchmarked exactly this with a lovely little video.

His video and site claimed that while was faster than for, I wanted to test this for myself, but I noticed he hadn’t provided us with his code, meaning I had to rewrite it.

I decided to improve on it slightly and provide both results one after another. Because of this I also decided to get rid of the memory usage that would now be affected by running both functions in the one script.

Don’t worry about this though, the memory usage was insignificantly different anyway (while was less). We’re interested in the speed more than anything. Here’s the code:

<?php

// for() vs while() loop benchmark test v0.1 by HM2K (09/09/08)

echo ‘PHP v’,phpversion(),’<br>’;

/* benchmark functions */

include(‘Benchmark/Iterate.php’);

function benchmark ($n,$t=100) {
$b=new Benchmark_iterate();
$b->run($t, $n);
$r=$b->get();
echo $n,’ Mean time: ‘,$r['mean'],’<br>’;
}

/* things to benchmark */

benchmark(‘testfor’);
benchmark(‘testwhile’);

/* test functions */

function testfor(){
for($i=0; $i<10000;++$i){
}
}
function testwhile(){
$i=0;
while ($i<10000){
++$i;
}
}

?>

Note: you will need the PEAR benchmark package.

The great thing about this script is it is totally reusable for all sorts of PHP benchmarking, but enough about the script, let’s get back to the benchmarking.

Using the script I was very quickly able to gather the results…

PHP v5.1.6
testfor Mean time: 0.0030984044075012
testwhile Mean time: 0.0027758502960205

Thus in conclusion WHILE is faster than FOR.

Related posts:

  1. 50+ PHP optimisation tips revisited After reading an article some time ago entitled “40 Tips...

Leave a Comment