Hi,

Saturday, March 27, 2004, 4:45:38 AM, you wrote:
CWP> hi.

CWP> ok, so i've always been under the impression that count()ing during the
CWP> expression of a loop was much inefficient when compared to count()ing
CWP> just before the loop expression.

CWP> GOOD:

CWP> <?php

CWP>   $the_array_cnt = count($the_array);
CWP>   for($i = 0; $i < $the_array_cnt; $i++)
CWP>   {
CWP>     ...
CWP>   }

?>>

CWP> BAD:

CWP> <?php

CWP>   for($i = 0; $i < count($the_array); $i++)
CWP>   {
CWP>     ...
CWP>   }

?>>

CWP> but then i did some tests and found that only on very large arrays is
CWP> there any difference between the two. count()ing outside of the loop was
CWP> only marginally better.

CWP> i also tried performing the same operation using foreach() and it was
CWP> slightly faster than count()ing within the loop and slightly slower than
CWP> count()ing outside the loop.

CWP> somone pointed out in a post to a message board that php handles the
CWP> result of a count() in a special way and so it therefore does not need
CWP> to count the array more than once each pass through the loop? can
CWP> someone confirm?



CWP> thanks,
CWP> chris.

CWP> --
CWP> PHP General Mailing List (http://www.php.net/)
CWP> To unsubscribe, visit: http://www.php.net/unsub.php


Depends on your code logic, if $the_array gets modified in the loop
then you have to check it on each pass. If not, efficiency would
suggest doing it before the loop. You can always do the 1 line
version:

for ($i=0,$j=count($the_array);$i<$j;$i++){

-- 
regards,
Tom

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to