note 95179 added to function.sizeof

From: Date: Wed, 16 Dec 2009 23:47:42 +0000
Subject: note 95179 added to function.sizeof
Groups: php.notes 
Request: Send a blank email to php-notes+get-164062@lists.php.net to get a copy of this message
The previous note by Emil Mohamed with the test runs is true only if you don't want to do anything with the values in the array. If you want to actually use the array values, foreach is faster. I edited his script as follows, assigning the value of the array element to $res: <?php $arr = array(); $num = 1000000; echo "Populating test array with $num elements ... "; for($i=0; $i<$num; $i++) { $arr[$i] = microtime(true) . mt_rand(); } echo "Populated.\n\n"; echo "Start testing FOREACH ... \n"; $start_time = microtime(true); foreach ($arr as $i=>$elem) { $res = $elem; } echo "FOREACH result: " . (microtime(true) - $start_time) . "\n\n"; echo "Start testing regular FOR ... \n"; $start_time = microtime(true); for ($i=0; $i<sizeof($arr); $i++) { $res = $arr[$i]; } echo "Regular for result: " . (microtime(true) - $start_time) . "\n\n"; echo "Starting test for pre-computed size array FOR ... \n"; $start_time = microtime(true); $sizeof_arr = sizeof($arr); for ($i=0; $i<$sizeof_arr; $i++) { $res = $arr[$i]; } echo "pre-computed size of array FOR: " . (microtime(true) - $start_time) . "\n"; ?> And got this output: Populating test array with 1000000 elements ... Populated. Start testing FOREACH ... FOREACH result: 0.156778097153 Start testing regular FOR ... Regular for result: 0.336126089096 Starting test for pre-computed size array FOR ... pre-computed size of array FOR: 0.164707899094 Which stayed consistent for the three runs that I did. It seems that the extra slowness of FOREACH in Emil's example is from the assignment of $elem, which is not available in either FOR, and needs to be done within the loop, as my test does. Given this, FOREACH is indeed faster. ---- Server IP: 69.147.83.197 Probable Submitter: 24.18.143.208 ---- Manual Page -- http://www.php.net/manual/en/function.sizeof.php Edit -- https://master.php.net/note/edit/95179 Del: integrated -- https://master.php.net/note/delete/95179/integrated Del: useless -- https://master.php.net/note/delete/95179/useless Del: bad code -- https://master.php.net/note/delete/95179/bad+code Del: spam -- https://master.php.net/note/delete/95179/spam Del: non-english -- https://master.php.net/note/delete/95179/non-english Del: in docs -- https://master.php.net/note/delete/95179/in+docs Del: other reasons-- https://master.php.net/note/delete/95179 Reject -- https://master.php.net/note/reject/95179 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#164062) next »