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

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;>

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

in_array()

foreach

array_search()

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

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)