note 30788 added to function.count

From: Date: Fri, 28 Mar 2003 14:26:55 +0000
Subject: note 30788 added to function.count
Groups: php.notes 
Request: Send a blank email to php-notes+get-45952@lists.php.net to get a copy of this message
(tested on both PHP 4.0.6, and 4.1.1) Count appears to be an Order N operation on an array of size N. This is problematic if you have it inside a for loop like this: for ($i=0;$i<count($array);$i++) { Some Code } Where $array is large >~4 or 500. Each iteration of the loop It appears to itterate through the entire array to figure out its size. The solution is to do count once before the for loop instead of inside it each time. $tCount = count($array); for ($i=0;$i<$tCount;$i++) { Some Code if ($someVar==4) { array_splice($array,$i,1); $tCount--; } } If the size of your array changes inside the for loop, just change the $tCount variable whenever you increment or decrement the size of the array. Josh PS this "features" of php's count can be responsible for as much as a 100x reduction in speed. -- http://www.php.net/manual/en/function.count.php http://master.php.net/manage/user-notes.php?action=edit+30788 http://master.php.net/manage/user-notes.php?action=delete+30788 http://master.php.net/manage/user-notes.php?action=reject+30788

« previous php.notes (#45952) next »