php – 为什么不同的测试顺序会得到不同的结果?

我更改了测试顺序并获得了不同的结果.我尝试禁用操作码缓存,添加未设置,但仍然得到不同的结果.为什么?

http://snipplr.com/view/759/

$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秒为array []花了0.122565秒

将测试数量增加到500000:

对于array_],取得0.779719秒,为array_push取得0.757806秒

array_push花了1.008018秒为array []花了0.494230秒

看看我是否更改了测试订单.这是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_push()之后的array []不需要花费时间,而是array []之后的array_push().

或者,也许这是一个谵妄

ps:所以,为了提高性能,我们必须调用一个消耗大量内存并且不会在脚本开头清理的函数?! %|

点赞