Home > php教程 > php手册 > body text

php中使用in_array() foreach array_search() 查找数组是否包含时的性能对比,phpforeach二维数组

WBOY
Release: 2016-06-13 09:06:56
Original
1744 people have browsed it

php中使用in_array() foreach array_search() 查找数组是否包含时的性能对比,phpforeach二维数组

判断某字符是否包含与某于数组中,方法有很多,刚学习php的新手们估计偏向于使用循环来解决,对于一般的小网站来说,这种解决方案是不会出现什么大问题的。但就性能来说,这种方法不是最好的方法,下面笔者就 foreach,in_array() array_search 这三种方法来比较这三种方法在性能表现上的差异。

<&#63;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);
  }
}
&#63;>
Copy after login

以上程序执行时间如下图所示:

in_array()

foreach

array_search()

由上可以大致看出这三种方法在性能上的表现了吧,array_search 和 in_array 表现差不多,foreach 表现最差。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!