$array = [];for($i=0; $i < 100; $i++)$array["key$i"] = $i;
for($i=0, $start = microtime(true); $i < 1000000; $i++) {foreach ($array as $firstKey => $firstValue) {break;}}echo "foreach to get first key and value: " . (microtime(true) - $start) . " seconds <br />";
for($i=0, $start = microtime(true); $i < 1000000; $i++) {$firstValue = reset($array);$firstKey = key($array);}echo "reset+key to get first key and value: " . (microtime(true) - $start) . " seconds <br />";
for($i=0, $start = microtime(true); $i < 1000000; $i++) {reset($array);$firstKey = key($array);}echo "reset+key to get first key: " . (microtime(true) - $start) . " seconds <br />";
for($i=0, $start = microtime(true); $i < 1000000; $i++) {$firstKey = array_keys($array)[0];}echo "array_keys to get first key: " . (microtime(true) - $start) . " seconds <br />";
在我的php 5.5上输出:
foreach to get first key and value: 0.15501809120178 secondsreset+key to get first key and value: 0.29375791549683 secondsreset+key to get first key: 0.26421809196472 secondsarray_keys to get first key: 10.059751987457 seconds
foreach to get first key and value: 0.048566102981567 secondsreset+key to get first key and value: 0.11727809906006 secondsreset+key to get first key: 0.11707186698914 secondsarray_keys to get first key: 0.53917098045349 secondsarray_slice to get first key: 0.2494580745697 seconds
如果我对大小为10000的数组执行此操作,则结果变为
foreach to get first key and value: 0.048488140106201 secondsreset+key to get first key and value: 0.12659382820129 secondsreset+key to get first key: 0.12248802185059 secondsarray_slice to get first key: 0.25442600250244 seconds