note 37068 modified in function.substr by aidan

From: Date: Sat, 03 Jul 2004 07:44:39 +0000
Subject: note 37068 modified in function.substr by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-72366@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. <?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. --was-- 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. http://php.net/manual/en/function.substr.php

« previous php.notes (#72366) next »