[英]Why is $arr[] = 'x' faster than $arr[0] = 'x'
I have the following: 我有以下内容:
# a.php
for($i=1; $i<=5000000; $i++) {
$arr = [];
for($f = 1; $f <= 5; $f++) {
$arr[$f] = 'a'; # <-- I am passing an index manually
}
}
And this: 和这个:
# 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
}
}
Why is b.php
code faster than a.php
code?... 为什么
b.php
代码比a.php
代码快?
In b.php
I am not passing an index manually, so PHP calculates it (isn't this slower?), and a.php
passes a defined index to that array, so I'm confused about this 在
b.php
我没有手动传递索引,因此PHP会对其进行计算(这不是更慢吗?),而a.php
将已定义的索引传递给该数组,因此我对此感到困惑
Used npm's gnomon package for time measurement 使用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
And 和
~/$ 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
In the first solution, php has to figure out what index must be used to set the new value and check if we are going to update existed element or add a new one. 在第一个解决方案中,php必须找出必须使用哪个索引来设置新值,并检查是否要更新现有元素或添加新元素。
In b.php
new element is always put on the end of the array, the additional check of index is not required. 在
b.php
新元素总是放在数组的末尾,不需要额外的索引检查。 This is basically how stack works. 基本上,这就是堆栈的工作方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.