
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements