Performance of FOR vs FOREACH in PHP

PHPServer Side ProgrammingProgramming

The 'foreach' is slow in comparison to the 'for' loop. The foreach copies the array over which the iteration needs to be performed.

For improved performance, the concept of references needs to be used. In addition to this, ‘foreach’ is easy to use.

Example

Below is a simple code example −

 Live Demo

<?php
   $my_arr = array();
   for ($i = 0; $i < 10000; $i++) {
      $my_arr[] = $i;
   }
   $start = microtime(true);
   foreach ($my_arr as $k => $v) {
      $my_arr[$k] = $v + 1;
   }
   echo "This completed in ", microtime(true) - $start, " seconds";
   echo "<br>";
   $start = microtime(true);
   foreach ($my_arr as $k => &$v) {
      $v = $v + 1;
   }
   echo "This completed in ", microtime(true) - $start, " seconds";
   echo "<br>";
   $start = microtime(true);
   foreach ($my_arr as $k => $v) {}
   echo "This completed in ", microtime(true) - $start, " seconds";
   echo "<br>";
   $start = microtime(true);
   foreach ($my_arr as $k => &$v) {}
   echo "This completed in ", microtime(true) - $start, " seconds";
?>

Output

This will produce the following output −

This completed in 0.00058293342590332 seconds
This completed in 0.00063300132751465 seconds
This completed in 0.00023412704467773 seconds
This completed in 0.00026583671569824 seconds
raja
Published on 30-Dec-2019 11:22:06
Advertisements