note 37951 added to control-structures.foreach

From: Date: Wed, 03 Dec 2003 07:48:31 +0000
Subject: note 37951 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-61307@lists.php.net to get a copy of this message
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 ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+37951 Delete -- http://master.php.net/manage/user-notes.php?action=delete+37951&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+37951&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#61307) next »