views:

74

answers:

4

Does anyone know if doing this

foreach ($user->getFriends() as $friend) {
  // Do something.
}

Causes PHP to call the function getFriends() on the user object multiple times and thus would this be more efficient?

$friends = $user->getFriends();
foreach ($friends as $f) {
 // Do something.
}
A: 

It depends how you want to use the underlying data. As you are iterating the fastest thing to do is use a for loop, predefining its upper boundary (so you arent, say, iterating a count function).

$limit=count($records);
for ( i=0; $i<$limit; i++){
    // do this code;
}
Ergo Summary
+2  A: 

I don't think the getFriends() method in this case would be called multiple times.

foreach makes a copy of the array to iterate over, and then iterates over the copy. There's no reason to call your method more than once.

The copying itself (and the resulting use of memory) is what you should consider when using a foreach loop.

Thomas
+1 for mentioning memory usage.
richsage
+5  A: 

foreach uses the result of the expression $user->getFriends(). You could look at it like this:

foreach (($user->getFriends()) as $friend) {
    // ...
}

The function is not going to be called more than once, since you pass its result and not the function itself. foreach does not know about the function.

elusive
A: 

try to look here http://www.phpbench.com/

albertopriore