PHP: Fastest way to handle undefined array key

后端 未结 8 1645
梦如初夏
梦如初夏 2020-12-08 07:13

in a very tight loop I need to access tenthousands of values in an array containing millions of elements. The key can be undefinied: In that case it shall be legal to return

8条回答
  •  一整个雨季
    2020-12-08 08:01

    I did some bench marking with the following code:

    set_time_limit(100);
    
    $count = 2500000;
    $search_index_end = $count * 1.5;
    $search_index_start = $count * .5;
    
    $array = array();
    for ($i = 0; $i < $count; $i++)
        $array[md5($i)] = $i;
    
    $start = microtime(true);
    for ($i = $search_index_start; $i < $search_index_end; $i++) {
        $key = md5($i);
        $test = isset($array[$key]) ? $array[$key] : null;
    }
    $end = microtime(true);
    echo ($end - $start) . " seconds
    "; $start = microtime(true); for ($i = $search_index_start; $i < $search_index_end; $i++) { $key = md5($i); $test = array_key_exists($key, $array) ? $array[$key] : null; } $end = microtime(true); echo ($end - $start) . " seconds
    "; $start = microtime(true); for ($i = $search_index_start; $i < $search_index_end; $i++) { $key = md5($i); $test = @$array[$key]; } $end = microtime(true); echo ($end - $start) . " seconds
    "; $error_reporting = error_reporting(); error_reporting(0); $start = microtime(true); for ($i = $search_index_start; $i < $search_index_end; $i++) { $key = md5($i); $test = $array[$key]; } $end = microtime(true); echo ($end - $start) . " seconds
    "; error_reporting($error_reporting); $start = microtime(true); for ($i = $search_index_start; $i < $search_index_end; $i++) { $key = md5($i); $tmp = &$array[$key]; $test = isset($tmp) ? $tmp : null; } $end = microtime(true); echo ($end - $start) . " seconds
    ";

    and I found that the fastest running test was the one that uses isset($array[$key]) ? $array[$key] : null followed closely by the solution that just disables error reporting.

提交回复
热议问题