gpt4 book ai didi

php - PHP 中哪个更快,$array[] = $value 还是 array_push($array, $value)?

转载 作者:IT老高 更新时间:2023-10-28 11:51:54 30 4
gpt4 key购买 nike

在 PHP 中附加数组成员更好用,

$array[] = $value;

array_push($array, $value);

?

虽然手册上说最好避免函数调用,但我也读过 $array[]array_push() 慢得多。有哪些说明或基准?

最佳答案

我个人觉得 $array[] 看起来更干净,老实说,在毫秒内拆分头发是无关紧要的,除非您计划将数十万个字符串附加到您的数组中。

我运行了这段代码:

$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
$array[] = $i;
}
print microtime(true) - $t;
print '<br>';
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
array_push($array, $i);
}
print microtime(true) - $t;

使用 $array[] 的第一种方法比第二种方法快 50%。

一些基准测试结果:

Run 1
0.0054171085357666 // array_push
0.0028800964355469 // array[]

Run 2
0.0054559707641602 // array_push
0.002892017364502 // array[]

Run 3
0.0055501461029053 // array_push
0.0028610229492188 // array[]

这不足为奇,正如 PHP 手册所指出的那样:

If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

如果 array_push 在添加多个值时效率更高,我不会感到惊讶。出于好奇,我做了一些进一步的测试,即使对于大量的添加,单独的 $array[] 调用也比一个大的 array_push 调用要快。很有趣。

关于php - PHP 中哪个更快,$array[] = $value 还是 array_push($array, $value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/559844/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com