猿问

为什么 $arr[] = 'x' 比 $arr[0] = 'x' 快

我有以下内容:


# a.php

for($i=1; $i<=5000000; $i++) {

    $arr = [];

    for($f = 1; $f <= 5; $f++) {

        $arr[$f] = 'a'; # <-- I am passing an index manually

    }

}

和这个:


# b.php

for($i=1; $i<=5000000; $i++) {

    $arr = [];

    for($f = 1; $f <= 5; $f++) {

        $arr[] = 'a'; # <-- Note that I am not passing an index manually

    }

}

为什么b.php代码比代码快a.php?...


在b.php我没有手动传递索引,所以 PHP 计算它(这不是更慢吗?),a.php并将定义的索引传递给该数组,所以我对此感到困惑


使用 npm 的 gnomon 包进行时间测量


~/$ php a.php | gnomon

   1.0981s   


     Total   1.0985s


~/$ php a.php | gnomon

   1.1350s   


     Total   1.1358s


~/$ php a.php | gnomon

   1.1664s   


     Total   1.1668s


~/$ php a.php | gnomon

   1.1105s   


     Total   1.1108s


~/$ php a.php | gnomon

   1.1074s   


     Total   1.1078s


~/$ php a.php | gnomon

   1.0969s   


     Total   1.0973s


~/$ php a.php | gnomon

   1.0872s   


     Total   1.0875s


~/$ php a.php | gnomon

   1.0992s   


     Total   1.0996s


~/$ php b.php | gnomon

   0.8960s   


     Total   0.8984s


~/$ php b.php | gnomon

   0.8859s   


     Total   0.8863s


~/$ php b.php | gnomon

   0.9031s   


     Total   0.9035s


~/$ php b.php | gnomon

   0.9078s   


     Total   0.9083s


~/$ php b.php | gnomon

   0.8880s   


     Total   0.8884s


~/$ php b.php | gnomon

   0.8945s   


     Total   0.8951s


~/$ php b.php | gnomon

   0.8891s   


     Total   0.8896s


~/$ php test.php | gnomon

   0.8843s   


     Total   0.8847s


蓝山帝景
浏览 178回答 1
1回答

慕桂英3389331

在第一个解决方案中,php 必须弄清楚必须使用什么索引来设置新值并检查我们是要更新现有元素还是添加新元素。在b.php新元素总是放在数组的末尾,不需要额外的索引检查。这基本上就是堆栈的工作方式。
随时随地看视频慕课网APP
我要回答