php array_intersect() efficiency

前端 未结 5 1879
旧时难觅i
旧时难觅i 2020-12-03 22:38

consider the below script. two arrays with only three values.when i compare these two arrays using array_intersect(). the result is fast.

    

        
5条回答
  •  被撕碎了的回忆
    2020-12-03 23:34

    I implementing this simple code of comparing array_intersect and array_intersect_key,

    $array = array();
        for( $i=0; $i<130000; $i++)
            $array[$i] = $i;
        for( $i=200000; $i<230000; $i++)
            $array[$i] = $i;
        for( $i=300000; $i<340000; $i++)
            $array[$i] = $i;
    
        $array2 = array();
        for( $i=100000; $i<110000; $i++)
            $array2[$i] = $i;
        for( $i=90000; $i<100000; $i++)
            $array2[$i] = $i;
        for( $i=110000; $i<290000; $i++)
            $array2[$i] = $i;
    
        echo 'Intersect to arrays -> array1[' . count($array) . '] : array2[' . count($array2) . '] ' . '
    '; echo date('Y-m-d H:i:s') . '
    '; $time = time(); $array_r2 = array_intersect_key($array,$array2); echo 'Intercept key: ' . (time()-$time) . ' segs
    '; $time = time(); $array_r = array_intersect($array,$array2); echo 'Intercept: ' . (time()-$time) . ' segs
    ';

    the result....

    Intersect to arrays -> array1[200000] : array2[200000] 
    2014-10-30 08:52:52
    Intercept key: 0 segs
    Intercept: 4 segs
    

    In this comparing of the efficency between array_intersect and array_intersect_key, we can see the interception with keys it is much faster.

提交回复
热议问题