Page 1 of 1

Does while in this context have any cons over foreach?

Posted: Tue Sep 28, 2010 4:15 am
by Ketrel
Does using 'while' in this manner have any cons compared to using foreach?

Code: Select all

while(list($key,$val) = each($array))
vs

Code: Select all

foreach($array as $key=>$val)

Re: Does while in this context have any cons over foreach?

Posted: Tue Sep 28, 2010 7:00 am
by Weirdan
reset + while(list()=each()) is consistently slower than foreach() :

Code: Select all

weirdan@home:~$ time php -r ' $arr = range(1,1000); $i = 1000; while ($i-->0) foreach($arr as $item) {$item=0;} '

real	0m0.483s
user	0m0.412s
sys	0m0.016s
weirdan@home:~$ time php -r ' $arr = range(1,1000); $i = 1000; while ($i-->0) {reset($arr); while(list(,$item)=each($arr)) {$item=0;}} '

real	0m2.706s
user	0m2.636s
sys	0m0.004s

Re: Does while in this context have any cons over foreach?

Posted: Tue Sep 28, 2010 7:43 am
by Ketrel
Weirdan wrote:reset + while(list()=each()) is consistently slower than foreach() :

Code: Select all

weirdan@home:~$ time php -r ' $arr = range(1,1000); $i = 1000; while ($i-->0) foreach($arr as $item) {$item=0;} '

real	0m0.483s
user	0m0.412s
sys	0m0.016s
weirdan@home:~$ time php -r ' $arr = range(1,1000); $i = 1000; while ($i-->0) {reset($arr); while(list(,$item)=each($arr)) {$item=0;}} '

real	0m2.706s
user	0m2.636s
sys	0m0.004s
What if any additions were being appended, and reset wasn't used?