在 PHP 中,$array[] = $value 或 array_push($array, $value) 哪个更快? [英] Which is faster in PHP, $array[] = $value or array_push($array, $value)?

查看:22
本文介绍了在 PHP 中,$array[] = $value 或 array_push($array, $value) 哪个更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 中添加数组成员用什么更好,

What's better to use in PHP for appending an array member,

$array[] = $value;

array_push($array, $value);

?

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

Though the manual says you're better off to avoid a function call, I've also read $array[] is much slower than array_push(). What are some clarifications or benchmarks?

推荐答案

我个人觉得 $array[] 看起来更清晰,老实说,除非你计划,否则在几毫秒内分裂头发是无关紧要的将数十万个字符串附加到您的数组中.

I personally feel like $array[] is cleaner to look at, and honestly splitting hairs over milliseconds is pretty irrelevant unless you plan on appending hundreds of thousands of strings to your 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%.

The first method using $array[] is almost 50% faster than the second one.

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 手册所述:

This shouldn't be surprising, as the PHP manual notes this:

如果您使用 array_push() 向数组添加一个元素,最好使用 $array[] = 因为这样就没有调用函数的开销.

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 调用要快.有趣.

The way it is phrased I wouldn't be surprised if array_push is more efficient when adding multiple values. Out of curiosity, I did some further testing, and even for a large amount of additions, individual $array[] calls are faster than one big array_push. Interesting.

这篇关于在 PHP 中,$array[] = $value 或 array_push($array, $value) 哪个更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆