php中使用in_array() foreach array_search() 查找數(shù)組是否包含時的性能對比
更新時間:2015年04月14日 22:39:49 投稿:mdxy-dxy
這篇文章主要介紹了php中使用in_array() foreach array_search() 查找數(shù)組是否包含時的性能對比,需要的朋友可以參考下
判斷某字符是否包含與某于數(shù)組中,方法有很多,剛學習php的新手們估計偏向于使用循環(huán)來解決,對于一般的小網(wǎng)站來說,這種解決方案是不會出現(xiàn)什么大問題的。但就性能來說,這種方法不是最好的方法,下面筆者就 foreach,in_array() array_search 這三種方法來比較這三種方法在性能表現(xiàn)上的差異。
<?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 "執(zhí)行時間: ".$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);
}
}
?>
以上程序執(zhí)行時間如下圖所示:
in_array()
![]()
foreach
![]()
array_search()
![]()
由上可以大致看出這三種方法在性能上的表現(xiàn)了吧,array_search 和 in_array 表現(xiàn)差不多,foreach 表現(xiàn)最差。
您可能感興趣的文章:
- php數(shù)組函數(shù)序列之a(chǎn)rray_key_exists() - 查找數(shù)組鍵名是否存在
- php數(shù)組查找函數(shù)in_array()、array_search()、array_key_exists()使用實例
- php數(shù)組函數(shù)序列之in_array() 查找數(shù)組值是否存在
- php數(shù)組函數(shù)序列之in_array() - 查找數(shù)組中是否存在指定值
- php 操作數(shù)組(合并,拆分,追加,查找,刪除等)
- php實現(xiàn)在多維數(shù)組中查找特定value的方法
- PHP查找與搜索數(shù)組元素方法總結(jié)
- php在數(shù)組中查找指定值的方法
- PHP 冒泡排序 二分查找 順序查找 二維數(shù)組排序算法函數(shù)的詳解
- PHP的數(shù)組中提高元素查找與元素去重的效率的技巧解析
- PHP查找數(shù)組中只出現(xiàn)一次的數(shù)字實現(xiàn)方法【查找特定元素】
相關(guān)文章
PHP常用特殊運算符號和函數(shù)總結(jié)(php新手入門必看)
新手經(jīng)常會有一些PHP特殊符號的問題,這里把常用的特殊符號整理一下。如果你全部都會用,那就當是溫故知新吧2013-02-02

