note 92626 deleted from function.sizeof by thiago

From: Date: Sat, 01 Aug 2009 00:19:03 +0000
Subject: note 92626 deleted from function.sizeof by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-158978@lists.php.net to get a copy of this message
Note Submitter: Madbreaks ---- In response to Emil Mohamed's note: Thanks for posting the code, but you've overlooked the main point: the reason for using foreach, and what previous commentors were getting at, is that you don't need to re-access the array inside the loop since your "$elem" variable already contains the array's value at that index. No need to reference "$i" in the foreach clause for that matter (see 'followup 1'). In addition, there exists another possibility, using 'while' with a precalculated count of the array (see 'followup 2'). As I expected, this yields the fastest result. Here's your code mod'd to include the additional test cases. <?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 = isset($arr[$i]); } 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 = isset($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 = isset($arr[$i]); } echo "pre-computed size of array FOR: " . (microtime(true) - $start_time) . "\n\n"; echo "------------------------------\n\n"; echo "followup 1: Starting FOREACH test w/o redundant array access... \n"; $start_time = microtime(true); foreach ($arr as $elem) { $res = isset($elem); } echo "FOREACH result: " . (microtime(true) - $start_time) . "\n\n"; echo "followup 2: Starting WHILE test w/ pre-computed array size... \n"; $start_time = microtime(true); $sizeof_arr = sizeof($arr); $i=0; while($i++ < $sizeof_arr) { $res = isset($arr[$i]); } echo "pre-computed size of array WHILE: " . (microtime(true) - $start_time) . "\n\n"; ?> ...and the results: Populating test array with 1000000 elements ... Populated. Start testing FOREACH... FOREACH result: 0.202980995178 Start testing regular FOR ... Regular for result: 0.473114967346 Starting test for pre-computed size array FOR ... pre-computed size of array FOR: 0.177510023117 ------------------------------ followup 1: Starting FOREACH test w/o redundant array access... FOREACH result: 0.162297010422 followup 2: Starting WHILE test w/ pre-computed array size... pre-computed size of array WHILE: 0.15519785881 Cheers

« previous php.notes (#158978) next »