在PHP中,最好使用$ array [] = $ value或array_push($ array,$ value)? [英] What's better to use in PHP, $array[] = $value or array_push($array, $value)?

查看:86
本文介绍了在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[]看起来更干净,并且诚实地将头发分开几毫秒几乎是无关紧要的,除非您计划附加数百个数以千计的字符串添加到您的数组.

No benchmarks, but 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. EDIT: Out of curiosity, 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天全站免登陆