Home > php教程 > php手册 > PHP数组性能

PHP数组性能

WBOY
Release: 2016-06-06 19:45:20
Original
1606 people have browsed it

最近阅读了PHP数组相关实现原理的文章, 因为是hashTable链表的形式实现, 所以想用代码具体看一下对性能的影响, 测试了2,3组数据,不太满意, 就不贴出来分析了, 先贴代码, 后续还需要修改测试代码画曲线图来分析 说一下测试目的, 一个例子是通过取来说明PHP数

最近阅读了PHP数组相关实现原理的文章, 因为是hashTable+链表的形式实现, 所以想用代码具体看一下对性能的影响, 

测试了2,3组数据,不太满意, 就不贴出来分析了, 先贴代码, 后续还需要修改测试代码画曲线图来分析

说一下测试目的, 一个例子是通过取值来说明PHP数组是通过链表遍历来进行随机访问的,性能和foreach应该差不多(事实说明前者快很多,可能是底层优化过), 第二个例子是说明foreach是链表遍历,for是随机访问的遍历,前者性能高于后者,这个测试结果与猜测相符.

<span><?php </span></span>
Copy after login
function getValueTest(){
    //生成测试样本数组
    require_once '../../include/Timer.cls.php';
    $arr = array();
    $n = 10000;
    for ($i=1;$istart();
    for ($i=$n;$i>0;$i--){
        $value = 'a'.$i;
        $tmp = $arr[$value];
    }
    $Timer->stop();
    $time1 = $Timer->getTime();
    //通过遍历比较取值
    $Timer->start();
    for ($i=$n;$i>0;$i--){
        $value = 'a'.$i;
        foreach ($arr as $key => &$val){
            if ($val == $value){
                $tmp = $val;
                break;
            }
        }
    }
    $Timer->stop();
    $time2 = $Timer->getTime();
    unset($val);
    echo "time1 $time1 time2 $time2";
}

function compareWhile(){
    //生成测试样本数组
    require_once '../../include/Timer.cls.php';
    $arr = array();
    $n = 1000000;
    for ($i=$n;$i>0;$i--){
        $arr[$i] = $i;
    }
    $tmp = '';
    //遍历性能比较
    $Timer = new Timer();
    $Timer->start();
    for ($i=1;$istop();
    $time1 = $Timer->getTime();
    $Timer->start();
    foreach ($arr as $key => &$val){
        $tmp = $val;
    }
    $Timer->stop();
    $time2 = $Timer->getTime();
    unset($val);
    echo "time1 $time1 time2 $time2";
}
Copy after login



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