php 自定义求数组差集,效率比自带的array_diff函数还要快(转)

<?php
function array_different($array_1, $array_2) {
$array_2 = array_flip($array_2); //将数组键值调换

foreach ($array_1 as $key => $val) {
if (isset($array_2[$val])) {
unset($array_1[$key]);
}
}

return $array_1;
}

function runtime($mode = 0) {
static $t;

if (!$mode) {
$t = microtime();
return;
}

$t1 = microtime();
list($m0, $s0) = explode(" ", $t);
list($m1, $s1) = explode(" ", $t1);

return sprintf("%.3f", ($s1 + $m1 - $s0 - $m0) * 1000);
}

$array_1 = array();
$array_2 = array();

for ($i = 0; $i <= 5000; $i++) {
$array_1[$i] = mt_rand(0, 100);
$array_2[$i] = mt_rand(0, 100);
}

runtime(); //计时开始
$arr_diff = array_diff($array_1, $array_2);
echo runtime(1); //计时结束并输出计时结果
echo '<br>';

foreach ($arr_diff as $key => $val) {
echo $val.',';
}

runtime(); //计时开始
$arr_diff2 = array_different($array_1, $array_2);
echo runtime(2); //计时结束并且输出计时结果

foreach ($arr_diff2 as $key => $val) {
echo $val.',';
}

posted @ 2013-08-01 15:19  幻星宇  阅读(684)  评论(0编辑  收藏  举报