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

Why is $arr[] = 'x' faster than $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

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

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