PHP Benchmark - For vs While
24th March 2007People always ask me what statement is faster, so I've gone ahead and created a benchmark test using Apache's AB Benchmarking tool. There's no reason not to use For either, you can use it with any while statement but While in some cases mean's less lines, but i prefer speed than less lines of code. This article will contain the following information:
- File sources (copy and paste)
- Benchmark results
- My view on the results
The following two files, which are shown below, ive tested contain the following code;
while.php
<?php
$a=0;
while($a <=10){
echo $a, '<br />';
$a++;
}
?>
for.php
<?php
for($a=0; $a<=10; $a++){
echo $a, '<br />';
}
?>
The benchmark results
| Structure | Mean | Median | Max |
|---|---|---|---|
| While | 17 milliseconds | 15 milliseconds | 531 milliseconds |
| For | 16 milliseconds | 15 milliseconds | 359 milliseconds |
To be honest i think the for.php file looks alot neater than while.php, but that might just be me.
For is faster than while, by a few milliseconds. I would prefer using For anyway as it just looks more professional.