2

Possible Duplicate:
for vs foreach vs while which is faster for iterating through arrays in php

For each and while, which of these is faster, recommended, and what are their resource usages like?

Community
  • 1
  • 1
Famver Tags
  • 1,988
  • 2
  • 16
  • 18
  • 6
    If this is a true concern, I suspect you're using the wrong language and platform. – falstro Dec 27 '10 at 08:00
  • @amphetamachine, these wheels are carrying most of top top rated sites, lol :) The key word here is "true concern". The thing you really need is not a program language, but a programmer. endangered species novadays... – Your Common Sense Dec 27 '10 at 08:16

3 Answers3

2

foreach is optimized for iteration over collections. That's a fancy way of saying that it works best (and fastest) when you use it with arrays (and as of PHP5, objects). You can use while() to get the same effect as a foreach, but its not as efficient since you need to call list() inside the while loop.

foreach($array as $key => $value) written with a while is while(list($key,$value) = each($array)). You can see the number of extra calls that are needed.

Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
  • +1. The big downside of `foreach` is that you can't navigate within the collection, and you don't know when you've reached its end. – Pekka Dec 27 '10 at 08:01
  • 2
    The `foreach` loop will perform the same calls, only it is hidden from your eyes. Shorter code is not necessarily faster (although it might be, in this case). – GolezTrol Dec 27 '10 at 08:04
  • @Pekka not that big. And, still, the question itself is stupid one, you know. – Your Common Sense Dec 27 '10 at 08:27
  • @Col well, it *is* a big downside if you need to navigate inside the array. But I agree, the performance differences are really irrelevant – Pekka Dec 27 '10 at 08:31
  • @Pekka dunno what do you mean by "navigate", but if it's not "iterate" then foreach is just wrong tool for this – Your Common Sense Dec 27 '10 at 08:48
1

i think they should have the same speed. i prefer foreach because its safer.

yossi
  • 12,945
  • 28
  • 84
  • 110
1

That may depend on how you use them exactly. You can choose to pass an array by reference to the foreach loop. In that case there will not be made a copy of the entire array. Optimizations like this probably have more effect than choosing between foreach and while.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210