php array_intersect() efficiency

前端 未结 5 1878
旧时难觅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:08

    The fastest solution I found:

    function arrayIntersect($arrayOne, $arrayTwo) {
            $index = array_flip($arrayOne);
            $second = array_flip($arrayTwo);
    
            $x = array_intersect_key($index, $second);
    
            return array_flip($x);
    }
    

    Tests I have made looks like below:

    function intersect($arrayOne, $arrayTwo)
    {
        $index = array_flip($arrayOne);
        foreach ($arrayTwo as $value) {
            if (isset($index[$value])) unset($index[$value]);
        }
        foreach ($index as $value => $key) {
            unset($arrayOne[$key]);
        }
    
        return $arrayOne;
    }
    
    function intersect2($arrayOne, $arrayTwo)
    {
        $index = array_flip($arrayOne);
        $second = array_flip($arrayTwo);
    
        $x = array_intersect_key($index, $second);
    
        return array_flip($x);
    
    }
    
    for($i =0; $i < 1000000; $i++) {
        $one[] = rand(0,1000000);
        $two[] = rand(0,100000);
        $two[] = rand(0,10000);
    }
    
    $one = array_unique($one);
    $two = array_unique($two);
    
    $time_start = microtime(true);
    $res = intersect($one, $two);
    $time = microtime(true) - $time_start;
    
    echo "Sort time $time seconds 'intersect' \n";
    
    
    $time_start = microtime(true);
    $res2 = array_intersect($one, $two);
    $time = microtime(true) - $time_start;
    
    echo "Sort time $time seconds 'array_intersect' \n";
    
    
    $time_start = microtime(true);
    $res3 = intersect2($one, $two);
    $time = microtime(true) - $time_start;
    
    echo "Sort time $time seconds 'intersect2' \n";
    

    Results from php 5.6 :

    Sort time 0.77021193504333 seconds 'intersect' 
    Sort time 6.9765028953552 seconds 'array_intersect' 
    Sort time 0.4631941318512 seconds 'intersect2'
    

提交回复
热议问题