为什么$ 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
wangfang74wf 回答:为什么$ arr [] ='x'比$ arr [0] ='x'快

在第一个解决方案中,php必须弄清楚必须使用哪个索引来设置新值,并检查是否要更新现有元素或添加一个新元素。

b.php中,新元素总是 放在数组的末尾,不需要额外的索引检查。 stack基本上就是这样。

本文链接:https://www.f2er.com/3018947.html

大家都在问