What is more effective? For or Foreach in PHP

3

Some time ago I have been programming in php. And I had the following doubt regarding the efficiency of the resources and the speed of how they behave.

My question is this:

What function is more effective when traversing an array?

I was reading documentation where it indicates that foreach is done to traverse array. But the question is rather which has greater effectiveness, either because it accesses fewer methods or because it is much more native.

I leave an example to make it easier to understand:

Example For:

<?php 
     $colors = array("red", "green", "blue", "yellow"); 
     $cantidad = count($colors);    

     for ($i = 0; $i <= $cantidad $i++) {
         echo $colors[$i]."<br>";
     }
?>

Foreach example:

<?php 
     $colors = array("red", "green", "blue", "yellow"); 

     foreach ($colors as $value) {
         echo $value."<br>";
     }
?>

I appreciate the interest!

NOTE:

I am aware that at the level of only a couple of data, this is not reflected. But the idea is to present it at the level of many data

NOTE2:

As part of a response to the process slowing down if in my cycle for put count($colors) I decided to separate it so that only the for itself is measured, and not enter unnecessary methods.

    
asked by José Miguel Sepulveda 27.04.2017 в 17:19
source

5 answers

3

To traverse an array in PHP, and we talk about arrays a little big, type 10 thousand iterations, the most efficient will be with foreach.

  

A for with a i a number is the second fastest. Finally what   slower is to traverse the array with a for i < count (array) , because   whenever you increase i call the count function of the array.

Here is an example of execution.

$elements = array();

    ////
    // Array de  10,000 elementos con string aleatorio
    ////
    for($i = 0; $i < 10000; $i++) {
            $elements[] = (string)rand(10000000, 99999999);
    }

    $time_start = microtime(true);

    ////
    // for 
    ////
    for($i = 0; $i < count($elements); $i++) { }

    $time_end = microtime(true);
    $for_time = $time_end - $time_start;

    $time_start = microtime(true);

    ////
    // foreach 
    ////
    foreach($elements as $element) { }

    $time_end = microtime(true);
    $foreach_time = $time_end - $time_start;

    echo "For tardo: " . number_format($for_time * 1000, 3) . "msn";
    echo "Foreach tardo: " . number_format($foreach_time * 1000, 3) . "msn";
  

Output: Forward: 0.326msn

     

Foreach tardy: 0.124msn

NOTE:

In case of changing the next line

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

like this:

$contar = count($elements);
for($i = 0; $i < $contar; $i++) { }

The change is noticeable. And therefore ends up having a better performance cycle for

    
answered by 27.04.2017 / 17:35
source
1

With this simple algorithm you could calculate the time that each loop takes to travel through the same elements.

First having a Array with 10,000 random values of String :

$elementos = array();
for($i = 0; $i < 10000; $i++) {
    $elementos[] = (string)rand(10000000, 99999999);
}

We will use the two loops to do the time tests with the use of microtime functions:

$time_start = microtime(true);

// Bucle for
for($i = 0; $i < count($elementos); $i++) { }

$time_end = microtime(true);
$for_time = $time_end - $time_start;

$time_start = microtime(true);

// Bucle foreach
foreach($elementos as $elemento) { }

$time_end = microtime(true);
$foreach_time = $time_end - $time_start;

Finally we print the results:

echo "For tiempo: " . number_format($for_time * 1000, 3) . "ms\n";
echo "Foreach tiempo: " . number_format($foreach_time * 1000, 3) . "ms\n";

Depending on the computer that executes the program you will get some results or others, but it seems that the foreach is somewhat faster than the for .

My result:

For tiempo: 0.003ms 
Foreach tiempo: 0.001ms

Here you have the complete code of the test

    
answered by 27.04.2017 в 17:37
1

A benchmark has been published on this and the conclusion is as follows:

In all cases the foreach loop is substantially faster than the for and while () procedures.

    
answered by 27.04.2017 в 17:59
0

Based on your own codes and doing variation to increase the array and also make last modification of placing separately $contar = count($colors);

Code:

<?php   
$elements = array();

////
// Array de  10,000 elementos con string aleatorio
////
for($i = 0; $i < 773139; $i++) {
        $elements[] = (string)rand(10000000, 99999999);
}

$time_start = microtime(true);

////
// for 
////
$contar = count($elements);
for($i = 0; $i < $contar; $i++) { }

$time_end = microtime(true);
$for_time = $time_end - $time_start;

$time_start = microtime(true);

////
// foreach 
////
foreach($elements as $element) { }

$time_end = microtime(true);
$foreach_time = $time_end - $time_start;

echo "For tardo: " . number_format($for_time * 1000, 5) . "msn<br>";
echo "Foreach tardo: " . number_format($foreach_time * 1000, 5) . "msn";

?>

I leave the results since they did not update previous answers. And I leave the results where every cycle for always went better. I thank @Voiser for being pro-active with this topic

    
answered by 27.04.2017 в 18:12
0
"el for tardó"  "el foreach tardó"
109.44486msn    146.44790msn
119.28487msn    160.94422msn
142.61222msn    143.96286msn
 99.05100msn    122.46180msn
157.92990msn    144.73200msn
147.69983msn    168.13302msn
    
answered by 21.08.2018 в 00:05