
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
Performance of FOR vs FOREACH in PHP
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 −
<?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
- Related Articles
- Difference Between For and Foreach in PHP
- Foreach in C++ vs Java
- Iterator vs forEach in Java
- PHP foreach Loop.
- The internal working of the ‘foreach’ loop in PHP
- Multiple index variables in PHP foreach loop
- Parsing JSON array with PHP foreach
- Calling Stored Procedure inside foreach PHP Codeigniter
- Stripping last comma from a foreach loop in PHP?
- PHP Casting Variable as Object type in foreach Loop
- How to access and return specific value of a foreach in PHP?
- ‘AND’ vs ‘&&’ operators in PHP
- PHP readfile vs. file_get_contents
- Compare define() vs const in PHP
- PHP Generators vs Iterator objects

Advertisements