繁体   English   中英

为什么$ 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新元素总是放在数组的末尾,不需要额外的索引检查。 基本上,这就是堆栈的工作方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM