Performance of For VS Foreach in PHP

Performance of FOR vs FOREACH in PHP

My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy... The time difference is going to be minimal in most cases.

The big thing to watch for is:

for ($i = 0; $i < count($array); $i++) {

That's an expensive loop, since it calls count on every single iteration. So long as you're not doing that, I don't think it really matters...

As for the reference making a difference, PHP uses copy-on-write, so if you don't write to the array, there will be relatively little overhead while looping. However, if you start modifying the array within the array, that's where you'll start seeing differences between them (since one will need to copy the entire array, and the reference can just modify inline)...

As for the iterators, foreach is equivalent to:

$it->rewind();
while ($it->valid()) {
$key = $it->key(); // If using the $key => $value syntax
$value = $it->current();

// Contents of loop in here

$it->next();
}

As far as there being faster ways to iterate, it really depends on the problem. But I really need to ask, why? I understand wanting to make things more efficient, but I think you're wasting your time for a micro-optimization. Remember, Premature Optimization Is The Root Of All Evil...

Edit: Based upon the comment, I decided to do a quick benchmark run...

$a = array();
for ($i = 0; $i < 10000; $i++) {
$a[] = $i;
}

$start = microtime(true);
foreach ($a as $k => $v) {
$a[$k] = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {
$v = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

And the results:

Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you're modifying the array in the loop, it's several times faster to use references...

And the overhead for just the reference is actually less than copying the array (this is on 5.3.2)... So it appears (on 5.3.2 at least) as if references are significantly faster...

EDIT: Using PHP 8.0 I got the following:

Completed in 0.0005030632019043 Seconds
Completed in 0.00066304206848145 Seconds
Completed in 0.00016379356384277 Seconds
Completed in 0.00056815147399902 Seconds

Repeated this test numerous times and ranking results were consistent.

for loop vs while loop vs foreach loop PHP

which one is better for performance?

It doesn't matter.

what's the criteria to select a loop?

If you just need to walk through all the elements of an object or array, use foreach. Cases where you need for include

  • When you explicitly need to do things with the numeric index, for example:
  • when you need to use previous or next elements from within an iteration
  • when you need to change the counter during an iteration

foreach is much more convenient because it doesn't require you to set up the counting, and can work its way through any kind of member - be it object properties or associative array elements (which a for won't catch). It's usually best for readability.

which should be used when we loop inside another loop?

Both are fine; in your demo case, foreach is the simplest way to go.

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

Even if there is any kind of difference, that difference will be so small it won't matter at all.

If you have, say, one query to the database, it'll take so long compared to the loop iterating over the results that the eternal debate of for vs foreach vs while will not change a thing -- at least if you have a reasonable amount of data.

So, use :

  • whatever you like
  • whatever fits your programming standard
  • whatever is best suited for your code/application

There will be plenty of other things you could/should optimize before thinking about that kind of micro-optimization.



And if you really want some numbers (even if it's just for fun), you can make some benchmark and see the results in practice.

Why array_values is better than a foreach?

  1. Less code.
  2. Easier to understand code, because that's exactly what array_values is for, yet your foreach could do anything unless you read and understand it.
  3. array_values is a native PHP function implemented in C behind the scenes, and likely much more performant than custom PHP code.

PHP for loop vs. foreach with range

Traditional for loop is faster than foreach + range. The first one only uses integer comparison and increasing while the last one has to create an (possibly big) array and then extract each element by moving the internal array cursor and checking whether the end is reached.

If you execute this you can see that plain for is twice faster than foreach + range:

$t0 = microtime(true);
for ($i = 0; $i < 100000; $i++) {
}
echo 'for loop: ' . (microtime(true) - $t0) . ' s', PHP_EOL;

$t0 = microtime(true);
foreach (range(0, 100000) as $i) {
}
echo 'foreach + range loop: ' . (microtime(true) - $t0) . ' s', PHP_EOL;

It is better to use traditional for as a habit in the case you need to iterate a given number of times but at the end of the day you won't see big performance improvements in most scenarios (take into account that the example above iterates 100k times, if you reduce the number of iterations, the difference is smaller).

PHP - Is array_map faster than foreach?

I believe this answers your question and is current as of 2015-01-22

Performance of foreach, array_map with lambda and array_map with static function

array_map although more elegant is sadly slower in PHP. Particularly if using it with a closure.

Compare performance between loop(foreach) and query database mysql with 1000 rows in PHP?

Mostly, the first solution will be faster just because it reduces rows count that will be transferred from DB to PHP. Moreover if there is will be an index for age and address it may be more faster (but depends on source data).

Another advantage of using MySQL is caching data, so there is possibility that someone just has run the same query and MySQL can return exact data -- obviously it will increase performance.

While vs. Foreach is there an objective difference?

Both are looping constructs and as per you mentioned, preference is one of the main reason for choice. But sometimes its easier to think in one format than other.

For e.g. If we want to run the loop endlessly and break out based on some condition, then while would be a more expressive and readable choice.

while (true) {
if condition {
break;
}
}

Also when we want to read file line by line until the end of file, while dominates:

while (($line = fgets($handle)) !== false) {
}

But sometimes for or foreach dominates cases such as looping through set of records/list.

foreach (records as key => value) {
}

Another aspect of this is, "while" is preferred over "for" when underlying loop source is about to change inside the loop.



Related Topics



Leave a reply



Submit