php中使用in_array() foreach array_search() 查找數(shù)組是否包含時的性能對比
判斷某字符是否包含與某于數(shù)組中,方法有很多,剛學(xué)習(xí)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)文章
解析使用substr截取UTF-8中文字符串出現(xiàn)亂碼的問題
本篇文章是對使用substr截取UTF-8中文字符串出現(xiàn)亂碼的問題進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06PHP實現(xiàn)陽歷到農(nóng)歷轉(zhuǎn)換的類實例
這篇文章主要介紹了PHP實現(xiàn)陽歷到農(nóng)歷轉(zhuǎn)換的類,實例分析了陽歷轉(zhuǎn)換到陰歷的原理與實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03學(xué)習(xí)php設(shè)計模式 php實現(xiàn)策略模式(strategy)
這篇文章主要介紹了php設(shè)計模式中的適配器模式,使用php實現(xiàn)適配器模式,感興趣的小伙伴們可以參考一下2015-12-12