I've read up on some of the different optimizations that can be done with for
loops in PHP, and would like to gauge your opinion on this:
for ($x = 0; $x < 50000000; ++$x) {
}
What else could I do, in this basic example, to speed it up? Would Zend Optimizer help with something so basic? I know it seems silly and not a real use-case, but it's of particular interest to me.
Focus on readable maintainable code. Micro optimization is generally a bad thing because it leads to unreadable code. Check out what Jeff Atwood (stackexchange co-founder) has to say about it: http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html
Your loop currently does absolutely nothing, so it's as optimized as it's ever going to be. You need to worry about what goes on inside the loop, not supposedly optimizing a language construct.
The only advice that can be given to "optimize" a for
loop declaration is to avoid using something like a count()
function in the comparison since it might get needlessly re-evaluated 50 million times. ie:
$count = count($hugeArray);
for( $i=0; $i<$count; $i++ ) {
//actual code
}
Otherwise you should be FAR more concerned with the code inside your loop. Are there other loops inside your loops? Recursive calls? Blocking/locking operations? Streamlining the code between the {
and }
will get you FAR better returns than worrying about for
using a few dozen extra clock cycles every day.