php 求数组交集之优化

来源:互联网 发布:淘宝公司运营模式 编辑:程序博客网 时间:2024/06/05 04:45


网上流传的优化函数本人在使用的时候出现问题,做了一点改动,把原来的一个函数拆成两个,即 intersect()和 intersect_sub().

看下面的代码:    

$rand = function() {    $result = array();    for ($i = 0; $i < 100; null) {        $value = mt_rand(1, 10000);        if (!isset($result[$value])) {            $result[$value] = null;            $i++;        }    }    return array_keys($result);};$param_a = $rand();$param_b = $rand();$time = microtime(true);$result = intersect($param_a, $param_b);$time = microtime(true) - $time;echo "intersect: {$time}<br/><br/><br/>";$time = microtime(true);$result = array_intersect($param_a, $param_b);$time = microtime(true) - $time;echo "array_intersect: {$time}\n";function intersect() {    if (func_num_args() < 2) {        trigger_error('param error', E_USER_ERROR);    }    $args = func_get_args();    foreach ($args AS $arg) {        if (!is_array($arg)) {            trigger_error('param error', E_USER_ERROR);        }    }    $result = array_shift($args);    sort($result);    foreach ($args as $arg) {        sort($arg);        $result = intersect_sub($result, $arg);    }    return $result;}function intersect_sub($a, $b) {        $result = array();        $length_a = count($a);        $length_b = count($b);        for ($i = 0, $j = 0; $i < $length_a && $j < $length_b; null) {            if($a[$i] < $b[$j]) {                $i++;            } else if($a[$i] > $b[$j]) {                $j++;            } else {                $result[] = $a[$i];                $i++;                $j++;            }        }        return $result;    };

运行结果如下:

intersect: 0.0060269832611084array_intersect: 0.029041051864624 
从运行结果可以看出,优化后时间开销大约节省了4/5



原创粉丝点击