note 37068 added to function.substr

From: Date: Sat, 01 Nov 2003 14:08:36 +0000
Subject: note 37068 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-59632@lists.php.net to get a copy of this message
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. 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: $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. ---- Manual Page -- http://www.php.net/manual/en/function.substr.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+37068 Delete -- http://master.php.net/manage/user-notes.php?action=delete+37068&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+37068&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#59632) next »