Bug #73571 [Nab]: foreach() way slower than while(list($key,$value)=each($arr))

From: Date: Mon, 21 Nov 2016 09:36:42 +0000
Subject: Bug #73571 [Nab]: foreach() way slower than while(list($key,$value)=each($arr))
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-205504@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=73571&edit=1 ID: 73571 User updated by: spam2 at rhsoft dot net Reported by: spam2 at rhsoft dot net Summary: foreach() way slower than while(list($key,$value)=each($arr)) Status: Not a bug Type: Bug Package: Performance problem PHP Version: 7.0.13 Block user comment: N Private report: N New Comment: forget the extract() stuff reset($arr) is a bit unfair since it's a additional function call Previous Comments: ------------------------------------------------------------------------ [2016-11-21 09:19:14] requinix@php.net I'll skip the sarcastic response I had planned and instead point out that you didn't reset($arr). Additionally, using EXTR_SKIP gives extract() an advantage over the other two as it doesn't have to re/create variables on loops $x>1. With those two fixed I get Extract: 0.73130393028259 While: 10.98973608017 For-Each: 0.69374203681946 So it turns out that foreach is actually the fastest. ------------------------------------------------------------------------ [2016-11-21 08:56:54] spam2 at rhsoft dot net Description: ------------ since you depreacte each() with PHP 7.2 better fix foreach() before [harry@srv-rhsoft:/downloads]$ php each.php Extract: 0.031516075134277 While: 0.0004878044128418 For-Each: 0.11238217353821 Test script: --------------- [harry@srv-rhsoft:/downloads]$ cat each.php <?php $loops = 2000; for($x=1;$x<$loops;$x++) { $arr['key' . $x] = 'Test'; } echo "Extract: "; $start = microtime(true); for($x=1;$x<$loops;$x++) { extract($arr, EXTR_SKIP); } echo microtime(true) - $start . "\n"; echo "While: "; $start = microtime(true); for($x=1;$x<$loops;$x++) { while(list($key,$value)=each($arr)) { ${$key} = $value; } } echo microtime(true) - $start . "\n"; echo "For-Each: "; $start = microtime(true); for($x=1;$x<$loops;$x++) { foreach($arr as $key=>$value) { ${$key} = $value; } } echo microtime(true) - $start . "\n"; ?> ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=73571&edit=1

« previous php.bugs (#205504) next »