选择哈希的第N个元素的最快方法

use*_*291 6 php arrays

我有一个很大的哈希表(带有字符串索引的数组),并寻找一个快速从中挑选第一个(理想情况下也是第N个)元素的函数.array_shift()并且reset()对我的需求来说太慢了.

更新:我也没有寻找基于参考的解决方案,该函数应该接受表达式,如get_first(some_func_returning_array())

答案 array_slice方法(kudos Gumbo)似乎是胜利者.完整的基准测试代码

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);
Run Code Online (Sandbox Code Playgroud)

结果:

           dummy = 0.393
           slice = 0.433
          values = 0.824
         foreach = 0.929
           reset = 0.935
     array_shift = 0.954
            keys = 1.371
Run Code Online (Sandbox Code Playgroud)

Gum*_*mbo 7

使用array_slice得到公正的数组ñ个项目,并array_pop最终得到它:

$nthItem = array_pop(array_slice($arr, $n, 1));
Run Code Online (Sandbox Code Playgroud)