PHP數組交集的優化
假設我們正在運營一個手機相關的網站
假定每個參數會包含一千個左右的唯一結果(id int)
<?php
$rand = function() {
$result = array();
for ($i =
$value = mt_rand(
if (!isset($result[$value])) {
$result[$value] = null;
$i++;
}
}
return array_keys($result);
};
$param_a = $rand();
$param_b = $rand();
?>
注意
<?php
$time = microtime(true);
$result = array_intersect($param_a
$time = microtime(true)
echo "array_intersect: {$time}n";
?>
再來看看通過自定義方法intersect實現的性能
<?php
function intersect() {
if (func_num_args() <
trigger_error(
}
$args = func_get_args();
foreach ($args AS $arg) {
if (!is_array($arg)) {
trigger_error(
}
}
$intersect = function($a
$result = array();
$length_a = count($a);
$length_b = count($b);
for ($i =
if($a[$i] < $b[$j]) {
$i++;
} else if($a[$i] > $b[$j]) {
$j++;
} else {
$result[] = $a[$i];
$i++;
$j++;
}
}
return $result;
};
$result = array_shift($args);
sort($result);
foreach ($args as $arg) {
sort($arg);
$result = $intersect($result
}
return $result;
}
$time = microtime(true);
$result = intersect($param_a
$time = microtime(true)
echo "intersect: {$time}n";
?>
直覺上
array_intersect
intersect
需要提醒大家的是
$param_a = array(
$param_b = array(
var_dump(
array_intersect($param_a
intersect($param_a
);
array_intersect
intersect
也就是說
再唠叨一下
<?php
function intersect() {
if (func_num_args() <
trigger_error(
}
$args = func_get_args();
foreach ($args AS $arg) {
if (!is_array($arg)) {
trigger_error(
}
}
$result = array();
$data = array_count_values(
call_user_func_array(
);
foreach ($data AS $value => $count) {
if ($count >
$result[] = $value;
}
}
return $result;
}
?>
代碼更簡潔
參考
From:http://tw.wingwit.com/Article/program/PHP/201311/21179.html