note 35022 added to control-structures.while
| From: | (Hosh) | Date: | Fri, 15 Aug 2003 20:52:55 +0000 |
| Subject: | note 35022 added to control-structures.while | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-54242@lists.php.net to get a copy of this message | ||
I made a test traversing an array (simple, but long, numeric array with numeric keys). My test had a
cycle per method, and multiplied each array element by 100.. These were my results:
******************************************************
30870 Element Array Traversing
[test_time] [BEGINS/RESETS @ time_start = 1060977996.689]
0.2373 seg later -> while (list ($key, $val) = each ($array)) ENDS
[test_time] [BEGINS/RESETS @ time_start = 1060977996.9414]
0.1916 seg later -> while (list ($key,) = each ($array)) ENDS
[test_time] [BEGINS/RESETS @ time_start = 1060977997.1513]
0.1714 seg later -> foreach ($array AS $key=>$value) ENDS
[test_time] [BEGINS/RESETS @ time_start = 1060977997.3378]
0.0255 seg later -> while ($next = next($array)) ENDS
[test_time] [BEGINS/RESETS @ time_start = 1060977997.3771]
0.1735 seg later -> foreach ($array AS $value) ENDS
**************************************************************
foreach is fatser than a while (list - each), true.
However, a while(next) was faster than foreach.
These were the winning codes:
$array = $save;
test_time("",1);
foreach ($array AS $key=>$value)
$array[$key] = $array[$key] * 100;
test_time("foreach (\$array AS \$key=>\$value)");
$array = $save;
test_time("",1);
reset($array);
while ($next = next($array))
{ $key = key($array);
$array[$key] = $array[$key] * 100;
}
test_time("while (\$next = next(\$array))");
*********************************************************
The improvement seems huge, but it isnt that dramatic in real practice. Results varied... I have a
very long bidimensional array, and saw no more than a 2 sec diference, but on 140+ second scripts.
Notice though that you lose control of the $key value (unless you have numeric keys, which I tend
to avoid), but it is not always necessary.
I generally stick to foreach. However, this time, I was getting Allowed Memory Size Exceeded errors
with Apache. Remember foreach copies the original array, so this now makes two huge 2D arrays in
memory and alot of work for Apache. If you are getting this error, check your loops. Dont use the
whole array on a foreach. Instead get the keys and acces the cells directlly. Also, try and use
unset and Referencing on the huge arrays.
Working on your array and loops is a much better workaround than saving to temporary tables and
unsetting (much slower).
----
Manual Page -- http://www.php.net/manual/en/control-structures.while.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35022
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35022&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35022&report=yes