note 37951 deleted from control-structures.foreach by nlopess
| From: | nlopess@php.net | Date: | Sat, 27 Dec 2003 11:40:38 +0000 |
| Subject: | note 37951 deleted from control-structures.foreach by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-62540@lists.php.net to get a copy of this message | ||
Note Submitter:
----
I've been developing some code that needs to process a huge array of information pulled from a
database. I've learned that for() loops are much faster than foreach() loops. Now this is when
cycling through 20,000+ times, so most applications won't see a speed improvement, but for
those that do, it can make a big difference.
I discovered all the value copying and whatnot was taking 2-3 seconds - with NO code within the loop
- on a 3 GHz Linux box!
Loops running on small arrays don't seem to benefit much. For example, I used a for() loop to
run my original code multiple times (benchmark purposes) that used a foreach() loop and I
couldn't tell the foreach() was slowing things down much, because it wasn't. But as your
array grows, it takes longer to parse through, it seems. I didn't discover this until I
populated the database with 17,000 records.
Another issue with foreach() is memory usage. Just watching top, httpd would suddenly bloat when
running my code. And I mean really, really bloat. Using for() instead dropped the sudden bloat in
httpd by about 60%.
To use for() instead of foreach() just make sure you have a numeric array and use the same variable
you're incrementing up with for() as the key for your array and compare that value to the
result of count().
This took me hours of playing and some help from the php mailing list to figure out. I hope this
helps somebody else!
-Galen
http://www.zinkconsulting.com