php数组赋值方式性能比较

实现功能:给长度为 1000w 的数组赋值(键值为数字索引值 +1)

php版本:5.6.32

赋值方式:

  • arr[ ]
  • array_push( )

代码:

<?php
ini_set('memory_limit', '2048M');

$j = 10000000;

$arr = [];
$t   = microtime(true);
for ($i = 1; $i <= $j; $i++) {
    $arr[] = $i;
}
$t = microtime(true) - $t;
echo "arr[]: {$t}\n";

$arr = [];
$t   = microtime(true);
for ($i = 1; $i <= $j; $i++) {
    array_push($arr, $i);
}
$t = microtime(true) - $t;
echo "array_push: {$t}\n";

结果用时(s):


总结:

数组赋相同值情况下,arr[ ] 方式性能优于 array_push( ) 方式。

猜你喜欢

转载自blog.csdn.net/ZopaulCode/article/details/79465005