3v4l.org

run code in 300+ PHP versions simultaneously
<?php ## preperations; just a simple environment state $test_iterations = 100; $test_arr_size = 1000; // a shared function that makes use of the loop; this should // ensure no funny bussiness is happening to fool the test function test($input) { echo '<!-- '.trim($input).' -->'; } // for each test we create a array this should avoid any of the // arrays internal representation or optimizations from getting // in the way. // normal array $test_arr1 = array(); $test_arr2 = array(); $test_arr3 = array(); // hash tables $test_arr4 = array(); $test_arr5 = array(); for ($i = 0; $i < $test_arr_size; ++$i) { mt_srand(); $hash = md5(mt_rand()); $key = substr($hash, 0, 5).$i; $test_arr1[$i] = $test_arr2[$i] = $test_arr3[$i] = $test_arr4[$key] = $test_arr5[$key] = $hash; } ## foreach $start = microtime(true); for ($j = 0; $j < $test_iterations; ++$j) { foreach ($test_arr1 as $k => $v) { test($v); } } echo '<strong>foreach</strong> '.(microtime(true) - $start).'<br />'; ## foreach (using reference) $start = microtime(true); for ($j = 0; $j < $test_iterations; ++$j) { foreach ($test_arr2 as &$value) { test($value); } } echo '<strong>foreach</strong> (using reference) '.(microtime(true) - $start).'<br />'; ## for $start = microtime(true); for ($j = 0; $j < $test_iterations; ++$j) { $size = count($test_arr3); for ($i = 0; $i < $size; ++$i) { test($test_arr3[$i]); } } echo '<strong>for</strong> '.(microtime(true) - $start).'<br />'; ## foreach (hash table) $start = microtime(true); for ($j = 0; $j < $test_iterations; ++$j) { foreach ($test_arr4 as $k => $v) { test($v); } } echo '<strong>foreach</strong> (hash table) '.(microtime(true) - $start).'<br />'; ## for (hash table) $start = microtime(true); for ($j = 0; $j < $test_iterations; ++$j) { $keys = array_keys($test_arr5); $size = sizeOf($test_arr5); for ($i = 0; $i < $size; ++$i) { test($test_arr5[$keys[$i]]); } } echo '<strong>for</strong> (hash table) '.(microtime(true) - $start).'<br />';

preferences:
32.1 ms | 402 KiB | 5 Q