更棒的是在PHP $数组[] = $值或array_push($数组$值)来使用? [英] What's better to use in PHP $array[] = $value or array_push($array, $value)?
问题描述
什么是最好的PHP用于追加数组成员 $数组[] = $值
或 array_push($数组$值)
?
What's better to use in PHP for appending an array member $array[] = $value
or array_push($array, $value)
?
虽然手册上说你最好避免函数调用,我也看到了 $数组[]
比慢得多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()
. Does anyone have any clarifications or benchmarks?
推荐答案
没有基准,但我个人觉得像 $数组[]
是清洁一下,老老实实在毫秒鸡蛋里挑骨头是pretty无关,除非你打算追加十万串到你的数组中。
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.
修改:这冉code:
$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;
使用第一种方法 $数组[]
比第二个快了近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()将一个元素添加到阵列中,最好使用$数组[] =,因为这样没有调用函数的开销。
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_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_push($数组$值)来使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!