兩個大陣列foreach,找出相同的key數量,所用的時間對比

y0umer發表於2014-02-13
<?php
function microtime_float() {
	list($usec, $sec) = explode(" ", microtime());
	return ((float)$usec + (float)$sec);
}

for($i = 1;$i <= 10000;$i++) {
	$data_1[$i] = 1;
}
for($i = 1001;$i <= 600000;$i++) {
	$data_2[$i] = 1;
}

$time_start = microtime_float();
$num = 0;
foreach ($data_1 as $key => $value) {
	if ($data_2[$key]) {
		$num++;
	}
}
echo $num;
$time_end = microtime_float();
$delta_time = $time_end - $time_start;
echo `程式總用時:`.round($delta_time, 3).`秒。`;

$time_start = microtime_float();
$num = 0;
foreach ($data_2 as $key => $value) {
	if ($data_1[$key]) {
		$num++;
	}
}
echo $num;
$time_end = microtime_float();
$delta_time = $time_end - $time_start;
echo `程式總用時:`.round($delta_time, 3).`秒。`;
?>

結果:9000程式總用時:0.003秒。9000程式總用時:0.595秒。

foreach放小的陣列,速度比較快。


相關文章