

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Difference Between For and Foreach in PHP
- Iterator vs forEach in Java
- Foreach in C++ vs Java
- PHP foreach Loop.
- Parsing JSON array with PHP foreach
- Multiple index variables in PHP foreach loop
- Calling Stored Procedure inside foreach PHP Codeigniter
- The internal working of the ‘foreach’ loop in PHP
- PHP readfile vs. file_get_contents
- Load Testing vs Stress Testing vs Performance Testing – What's the Difference?
- 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?
- Compare define() vs const in PHP
- PHP Generators vs Iterator objects
Advertisements