[dev] For vs. Foreach

Michael M Slusarz slusarz at horde.org
Wed Feb 3 18:56:23 UTC 2010


Quoting Ronan SALMON <rsalmon at mbpgroup.com>:

>> commit 560d9d8ba41200dec93b839449b983ac8f61d49e
>> Author: Michael M Slusarz <slusarz at curecanti.org>
>> Date:   Mon Feb 1 15:46:18 2010 -0700
>>
>>   Just kidding - array_merge() is terrible slow
>>
>> framework/Imap_Client/lib/Horde/Imap/Client/Utils.php |    4 +++-
>> 1 files changed, 3 insertions(+), 1 deletions(-)
>
> Hi all,
>
> I always thought 'foreach' was faster than 'for' when dealing with  
> arrays. So I ran the following script on my machine (thanks to  
> http://derekgallo.com/2007/04/19/for-vs-foreach/) :

This has been noted in horde/doc/CODING_STANDARDS forever.

Additionally, at least as of PHP 4, foreach() can be significantly  
slower than while()/each().  This is because foreach() makes a copy of  
the entire input array while each() is providing references to  
elements in the array.

As of PHP 5 it is possible to tell foreach() to provide references  
instead, but I still prefer using while()/each() simply because it is  
a clearer coding style IMHO.

michael

-- 
___________________________________
Michael Slusarz [slusarz at horde.org]



More information about the dev mailing list