Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...