我更改了测试顺序并获得了不同的结果。我尝试禁用操作码缓存,添加未设置,但仍然得到不同的结果。为什么?
$time_start = microtime(true);
$myArray = array();
for ( $i = 0; $i < 100000; ++$i )
{
$myArray[] = $i;
$myArray[] = 'test a string';
}
$time_end = microtime(true);
printf("Took %f seconds for array[]\n", $time_end - $time_start);
$time_start = microtime(true);
$myArray = array();
for ( $i = 0; $i < 100000; ++$i )
{
array_push($myArray, $i);
array_push($myArray, 'test a string');
}
$time_end = microtime(true);
printf("Took %f seconds for array_push\n", $time_end - $time_start);
为array []花了0.145872秒为array_push花了0.154502秒
$time_start = microtime(true);
$myArray = array();
for ( $i = 0; $i < 100000; ++$i )
{
array_push($myArray, $i);
array_push($myArray, 'test a string');
}
$time_end = microtime(true);
printf("Took %f seconds for array_push\n", $time_end - $time_start);
$time_start = microtime(true);
$myArray = array();
for ( $i = 0; $i < 100000; ++$i )
{
$myArray[] = $i;
$myArray[] = 'test a string';
}
$time_end = microtime(true);
printf("Took %f seconds for array[]\n", $time_end - $time_start);
为array_push花了0.197076秒为数组[]
花了0.122565秒将测试编号增加到500000:
数组[]花了0.779719秒为array_push花了0.757806秒
为array_push花了1.008018秒为数组[]
花了0.494230秒看看我是否更改了测试订单。这是2倍的速度差异。
答案 0 :(得分:2)
我的想法是关于内存使用情况:我添加了memory_get_usage()
差异的回声(就像时间一样)并看到了这个:
Took 0.108744 seconds for array_push
memory: 32497848
Took 0.151069 seconds for array_push
memory: 320
和
Took 0.061715 seconds for array[]
memory: 32499584
Took 0.058831 seconds for array[]
memory: -40
所以:array_push()
似乎没有清理为脚本分配的内存,而array[]
似乎是这样做的。 php需要一些时间来分配新内存(我猜),因此array[]
之后array_push()
不需要花费时间,array_push()
array[]
之后。{ / p>
或者,也许是谵妄
ps:所以,为了提高性能,我们必须调用一个消耗大量内存并且不会在脚本开头清理的函数?! %|