Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOR loop performance in PHP

As my research leads me to believe that for loops are the fastest iteration construct in PHP... to make it clearer, which of the following do you think would be faster?

Example ONE

for ($i = 0; $i < count($myLargeArray); $i++ ) {
    echo myLargeArray[$i];
}

Example TWO

$count = count($myLargeArray);
for ($i = 0; $i < $count; $i++ ) {
    echo myLargeArray[$i];
}

My logic follows that on each iteration in example one accessing the length of myLargeArray on each iteration is more computationally expensive than accessing a simple integer value as in example two. Is that correct?

like image 846
AndrewMcLagan Avatar asked Nov 20 '12 03:11

AndrewMcLagan


Video Answer


2 Answers

The first way is slower because the count() function has to be called in every iteration of the loop. The count() method itself is pretty fast, but there is still some overhead in calling the function at all. By moving it outside the loop, you're performing what is called "loop invariant code motion", or sometimes "hoisting".

There's a whole family of optimizations like this that are interesting to learn about.

Having said all that, it seldom pays to stress about this very much. In your example here, the I/O of echoing the output is probably 10 times what you save through your "optimization". And if you do anything else at all inside your loop, your optimization means less and less.

I hate to be a wet blanket, but for more than 90% of your code, performance is a non-issue. Especially when you talk about web applications, which are more than 90% I/O to begin with.

Still, when you think your code is to blame, you should:

  1. Decide on the use case you need to optimize
  2. Measure your code performance
  3. Find the bottlenecks
  4. Identify the areas you can improve and decide whether it is worth your time to improve them.
  5. Make your code changes
  6. Go back to step 2

You'll nearly always discover that you need to improve your caching strategies and database optimization (which is just I/O optimization by another means), instead of twiddling code.

like image 95
slashingweapon Avatar answered Oct 01 '22 15:10

slashingweapon


The fastest construct in this case is actually the foreach loop:

foreach($myLargeArray as $element) {
    echo $element;
} 

The foreach() is also nice in that it'll always terminate, whereas a typo could leave you with an infinite loop when you use for().

like image 42
cleong Avatar answered Oct 01 '22 15:10

cleong