function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } function createRandomString($len = 8) { $chars = "abcdefghijkmnopqrstuvwxyz023456789"; srand((double)microtime()*1000000); $i = 0; $pass = '' ; while ($i <= $len) { $num = rand() % 33; $tmp = substr($chars, $num, 1); $pass = $pass . $tmp; $i++; } return $pass; } $max_element = 1000; // Initialize array, filling random keys and values for ($i = 0; $i <= $max_element; $i++) { $test_array[createRandomString(8)] = createRandomString(64); } function ForEachLoop() { global $test_array; foreach ($test_array as $ele) { $tmp[] = $ele; } } function WhileListEachLoop() { global $test_array; while (list(, $ele) = each($test_array)) { $tmp[] = $ele; } } function ForEachLoopWithKey() { global $test_array; foreach ($test_array as $k=>$ele) { $tmp[] = $ele; } } function WhileListEachLoopWithKey() { global $test_array; while (list($k, $ele) = each($test_array)) { $tmp[] = $ele; } } function GetKeyLoop() { global $test_array; $keys = array_keys($test_array); $count = sizeOf($keys); for ($i=0; $i<$count; $i++) { $tmp[] = $test_array[$keys[$i]]; } } $tests = array( 'ForEachLoop', 'WhileListEachLoop', 'ForEachLoopWithKey', 'WhileListEachLoopWithKey', 'GetKeyLoop' ); $test_score = array(); foreach ($tests as $test) { // Foreach test for ($a=1; $a<=5; $a++) { reset($test_array); $timestart = microtime_float(); call_user_func($test); $time_took = microtime_float() - $timestart; $test_score[$test][] = $time_took*1000; } } ?>
| Loop style | Test 1 | Test 2 | Test 3 | Test 4 | Test 5 | Average |
|---|---|---|---|---|---|---|
| =$test; ?> | foreach ($test_score[$test] as $score) { ?>=number_format($score, 2); ?> | } ?>=number_format(array_sum($test_score[$test])/sizeof($test_score[$test]), 2); ?> |