0

Intro

If I loop in PHP, and know how many times I want to iterate, I usually use the for-loop like this:

for($y=0; $y<10; $y++) {
    // ...
}

But lately I have seen someone use the foreach-loop:

foreach (range(1, 10) as $y) {
    // ...
}

Now, I found the foreach-loop much more readable and thought about adopt this foreach-construct. But on the other side the for-loop is faster as you can see in the following.

Speed Test

I did then some speed tests with the following results.

Foreach:

$latimes = [];
for($x=0; $x<100; $x++) {

    $start = microtime(true);

    $lcc = 0;
    foreach (range(1, 10) as $y) {
        $lcc ++;
    }

    $latimes[$x] = microtime(true) - $start;
}
echo "Test 'foreach':\n";
echo (float) array_sum($latimes)/count($latimes);

Results after I runnt it five times:

Test 'foreach': 2.2873878479004E-5
Test 'foreach': 2.2327899932861E-5
Test 'foreach': 2.9709339141846E-5
Test 'foreach': 2.5603771209717E-5
Test 'foreach': 2.2120475769043E-5

For:

$latimes = [];
for($x=0; $x<100; $x++) {

    $start = microtime(true);

    $lcc = 0;
    for($y=0; $y<10; $y++) {
        $lcc++;
    }

    $latimes[$x] = microtime(true) - $start;
}
echo "Test 'for':\n";
echo (float) array_sum($latimes)/count($latimes);

Results after I runnt it five times:

Test 'for': 1.3396739959717E-5
Test 'for': 1.0268688201904E-5
Test 'for': 1.0945796966553E-5
Test 'for': 1.3313293457031E-5
Test 'for': 1.9807815551758E-5

Question

What I like to know is what would you prefer and why? Which one is more readable for you, and would you prefer readability over speed?

6
  • 3
    What kind of high-end applications are you writing with PHP that would make premature optimizations like this even necessary? Commented Jan 3, 2014 at 11:04
  • Your test is wrong. In the foreach case, you are also calling range(). Try the same thing with an array. Commented Jan 3, 2014 at 11:05
  • 1
    I wonder why are you asking a question when you have experimented yourself Commented Jan 3, 2014 at 11:06
  • 1
    I used to get hooked on minor performance issues like this, and i still do sometimes. The thing to remember is you will probably never write any application that utilises enough of these performance differences to make any real difference. I try to be logical and favour what makes sense given the context of the code. If you have an array of stuff, use foreach, if you're looping based on an incrementing counter, use a for loop. Commented Jan 3, 2014 at 11:07
  • And this doesn't even include testing using PHP 5.5 Generators Commented Jan 3, 2014 at 11:09

1 Answer 1

0

The following code samples are written in php under codeigniter framework’s benchmark library(it just to save my time as i am currently using these :D ), if you are using other languages, consider this as a pseudo code implement in your language way. There shouldn’t be any problem to implement this to any programming language. If you have experience with php/codeigniter, then you are lucky, just copy paste this code and test :) .

$data = array();
for($i=0;$i<500000;$i++){
        $data[$i] = rand();
    }

$this->benchmark->mark('code_start');
    for($i=0;$i<500000;$i++){
        ;
    }
$this->benchmark->mark('code_end');
echo $this->benchmark->elapsed_time('code_start', 'code_end');
echo "<br/>";
$this->benchmark->mark('code_start');         
    foreach($data as $row){
        ;
    }
$this->benchmark->mark('code_end');

I have got 2 seconds difference between these two loops(one later one ran in around 3 seconds while first one ran in around 5 seconds). So, foreach loop won the ‘battle of for vs foreach’ here. However, you might be thinking, we won’t need such big loop; May be not in all cases, but there are some cases where long loops may be needed, like update big product database from web service/xml/csv etc. And, this example is only to aware you about the performance difference between them.

But, yes, they both have some exclusive use where they should exclusively because of extreme easiness/optimization. Like, if you are working in a loop where, on a certain condition the loop can be terminated. In this case, for loop will do the work with the most flexibility. On the other hand, if you are taking every objects/item from a list array and processing them, in this case, foreach will serve you best.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.