note 37068 deleted from function.substr by nlopess
| From: | nlopess@php.net | Date: | Sat, 03 Jul 2004 11:49:35 +0000 |
| Subject: | note 37068 deleted from function.substr by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72407@lists.php.net to get a copy of this message | ||
Note Submitter:
----
WARNING: sizeof()/count() calls on big arrays are expensive, don't do it in a loop!
For example I implemented a FOR loop that walks through an array. In the loop there was a call to
sizeof() because I needed to do something different if this was going to be the last time through
the loop.
<?php
for ($thisrow = 0; $thisrow < sizeof ($thisarray); $thisrow++)
{
if ($thisrow == (sizeof ($thisarray) - 1))
// This is the last time through the loop, do something different
else
// Not the last time through the loop, do something different
}
?>
I found that on an array with about 1000 entries this took 4 seconds!
After experimenting a little I found that the problem was the sizeof () call being made on each loop
iteration. I rewrote the code as follows:
<?php
$arraysize = sizeof ($thisarray);
for ($thisrow = 0; $thisrow < $arraysize; $thisrow++)
{
if ($thisrow == ($arraysize - 1))
// This is the last time through the loop, do something different
else
// Not the last time through the loop, do something different
}
?>
The rewritten function executed in about 0.1 seconds on the same 1000 entry array. The moral of
this story: Never use count or sizeof in a loop, under any circumstances whatsoever.