判斷某字符是否包含與某於數組中,方法有很多,剛學習php的新手們估計偏向於使用循環來解決,對於一般的小網站來說,這種解決方案是不會出現什麼大問題的。但就性能來說,這種方法不是最好的方法,下面筆者就 foreach,in_array() array_search 這三種方法來比較這三種方法在性能表現上的差異。
<?php
$runtime= new runtime;
$runtime->start();
$a = 'k';
$b = array('a','b','c','d','e','f','g','h','i','j','k');
/*
for ($i=0; $i < 100000; $i++) {
var_dump(in_array($a, $b));
}
*/
/*
for ($i=0; $i < 100000; $i++) {
foreach ($b as $key => $value) {
if ($a == $value) {
//echo TRUE;
continue;
}
}
}
*/
/*
for ($i=0; $i < 100000; $i++) {
array_search($a, $b);
}
*/
$runtime->stop();
echo $_b;
echo "執行時間: ".$runtime->spent()." 毫秒";
class runtime{
var $StartTime = 0;
var $StopTime = 0;
function get_microtime(){
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
function start(){
$this->StartTime = $this->get_microtime();
}
function stop(){
$this->StopTime = $this->get_microtime();
}
function spent(){
return round(($this->StopTime - $this->StartTime) * 1000, 1);
}
}
?>
以上程序執行時間如下圖所示:
in_array()
![]()
foreach
![]()
array_search()
![]()
由上可以大致看出這三種方法在性能上的表現了吧,array_search 和 in_array 表現差不多,foreach 表現最差。