English 中文(简体)
Are there performance issue of using while loop vs foreach/for loop?
原标题:

What are the performance issue of using while loop v/s foreach/for loop or vice-versa ?

Also is it always preferable to use foreach loop v/s while in php ?

最佳回答

You ve listed this as "language-agnostic," but the answer will be language (or, rather, compiler)-specific.

Theoretically, foreach can be just as fast, if not faster, especially if the regular for loop keeps doing an expensive operation to test the Count.

Also, foreach works for a lazy-loaded collection, a regular for loop must know the number of item ahead of time.

Finally, even if foreach is slightly slower on your platform, it is highly unlikely the difference will matter, and it is much more maintainable than a for loop. Don t prematurely optimize. (This was, incidentally, the case for .NET for while, they ve since tidied up the performance of enumerators.)

问题回答

Hypothetically, a foreach may be slower - a for loop and a while loop with the same condition should be equivalent.

foreach needs to go through the data structure at hand, so whatever the structure s lookup for next (and maintaining state) may slow you down.

However, if you re doing that manually in a for or while loop, then it s probably the same.

The best answer, of course, is try it and time it and see what the answer actually is.

I know this is years old, but I need to point something out for future googlers:

"foreach" requires the data you are pulling from to be loaded and complete - for example, the array you would loop will already be in memory.

"while" only requires a single value (can be data or false - whether to continue the loop). Programming your loop correctly, a while loop only needs to have the next value loaded as opposed to a whole data set. So if you were to program the while loop to draw its data from a function, you can dramatically cut down memory usage.

An example might be iterating through each row of a large million-row database; using foreach you ll need to load the entire dataset to perform the loop, which would eat your memory alive. but using a function that pulls only the next row needed, you would successfully complete the loop.

the below pseudocode explains:

function nextrow ()
{
  static myquery = sql_query( SELECT * FROM `hugetable` )
  return(next_row(myquery));
}
while(row = nextrow()) { ...do stuff... }

Short answer: no. It s not a useful thing to waste even a single thought on.

I wrote an article for php|architect on the very issue of looping in PHP. Basically, benchmarks show, that there s no significant impact from the looping overhead... even when using my lazy numeric range extension.

IIRC, foreach is 2.9x slower than a for loop, once you exclude memory and the costs of generator functions. If the contents of your loop are less than 2.9x of the loop overhead, then you might want to reconsider what you re doing.

Furthermore, if you re seeking raw loop performance in a language, PHP should be on your list of absolute last choices. It s interpreted and, separately, not well suited for long-running operations.

Most PHP coders waste innumerable cycles concatenating strings. This speaks to the premature optimization warnings. I bet I can double your performance simply by adding commas to your "echo" statements.

Profile your code with XDebug or something. Find your real bottlenecks. Looping isn t it. Trust me. It never is.





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签