Performance comparison of using in_array() foreach array_search() in php to find whether the array contains, phpforeach two-dimensional array_PHP tutorial

WBOY
Release: 2016-07-13 09:57:05
Original
1184 people have browsed it

Performance comparison when using in_array() foreach array_search() in php to find whether an array is contained, phpforeach two-dimensional array

determine whether a certain character is included in the array, method There are many. Newbies who have just learned PHP are probably more likely to use loops to solve it. For ordinary small websites, this solution will not cause any big problems. But in terms of performance, this method is not the best method. Below, the author will compare the performance differences of these three methods, foreach and 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

The execution time of the above program is shown in the figure below:

in_array()

关于使用in_array() foreach array_search() 查找数组是否包含时的性能对比

foreach

关于使用in_array() foreach array_search() 查找数组是否包含时的性能对比

array_search()

关于使用in_array() foreach array_search() 查找数组是否包含时的性能对比

From the above, you can roughly see the performance of these three methods. array_search and in_array perform almost the same, and foreach performs the worst.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/984627.htmlTechArticlePerformance comparison of using in_array() foreach array_search() in php to find whether the array contains, phpforeach two-dimensional array judgment There are many methods to determine whether a certain character is included in an array, just...
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template