Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Foreach Loop Efficiency

Tags:

arrays

php

I am using a foreach loop within PHP similar to this:

foreach ($class->getAttributes() as $attribute) {
// Work
}

Concerning efficiency, is it better to have a $attributes = $class->getAttributes(); statement outside the foreach loop and iterate over the $attributes variable? Or is the $class->getAttributes() statement only getting called once inside the foreach declaration at the beginning?

(I realize this might not be a big efficiency concern in this case, but I would like to know the principle for this and other larger cases)

Thanks,

Steve

like image 342
Stephen Watkins Avatar asked Feb 27 '10 17:02

Stephen Watkins


1 Answers

Using $class->getAttributes() outside of the foreach loop and using a temporary variable, or keeping it like you wrote should not change anything about performances : it will still be evaluated only once.

And here is an example that proves it :

function get_array() {
    echo 'function called !<br />';
    return array(
        'first' => 123,
        'second' => 456,
        'last' => 789, 
    );
}
foreach (get_array() as $key => $value) {
    echo "$key : $value<br />";
}

I am using a function and not a method of a class, to get a shorter example, but the principle would be the same with a class+method.


And calling this portion of code gives the following output :

function called !
first : 123
second : 456
last : 789

i.e. the get_array() function is only called once, at the beginning of the foreach loop.

like image 158
Pascal MARTIN Avatar answered Sep 20 '22 21:09

Pascal MARTIN