I have a large hash table (an array with string indexes) and search for a function that quickly selects the first (ideally, and Nth) element from it. array_shift() and reset() too slow for my needs.
UPDATE : I am also not looking for a reference solution, the function should accept expressions as in get_first(some_func_returning_array())
The ANSWER method array_slice (kudos Gumbo) seems to be the winner. Full test code
function bigary($n) { $a = array(); $s = range('A', 'Z'); do { shuffle($s); $a[substr(implode('', $s), rand(10, 20))] = $n; } while(--$n); return $a; } function timeit($name, $fn) { global $results; $loops = 1000; $size = 5432; static $a; if(!$a) $a = bigary($size); $t = microtime(1); for($i = 0; $i < $loops; $i++) $b = $fn($a); $results[$name] = microtime(1) - $t; } timeit('dummy', function ($a) { // benchmark php function call overhead }); timeit('array_shift', function ($a) { return array_shift($a); }); timeit('reset', function ($a) { return reset($a); }); timeit('foreach', function ($a) { foreach($a as $b) return $b; }); timeit('keys', function ($a) { $b = array_keys($a); return $a[$b[0]]; }); timeit('values', function ($a) { $b = array_values($a); return $b[0]; }); timeit('slice', function ($a) { $b = array_slice($a, 0, 1); return reset($b); }); asort($results); foreach($results as $name => $time) printf("%20s = %.3f\n", $name, $time);
Results:
dummy = 0.393 slice = 0.433 values = 0.824 foreach = 0.929 reset = 0.935 array_shift = 0.954 keys = 1.371
source share