在编写了一个小基准脚本之后,我想我已经找到了答案。这是脚本的代码:
<?php
$n_iteration = 1e7;
$test_sizes = array(
1e2, 1e3, 1e4, 1e5, 1e6, 2e6, 3e6, 4e6, 5e6
);
foreach ($test_sizes as $test_size){
$test_array = range(1, $test_size);
$start_time = microtime(true);
for ($i = 0; $i < $n_iteration; $i++)
{ $x = count($test_array); }
$end_time = microtime(true);
$interval = $end_time - $start_time;
printf(
"Iterations: %d, Size: %8.d,"
." Total time: %6.3f sec, Avg. time: %1.3e sec\n",
$n_iteration, $test_size, $interval, $interval/$n_iteration);
}
使用“PHP 5.4.4-2 (cli) (built: Jun 19 2012 07:38:55)”在我的机器上运行脚本会产生以下输出:
Iterations: 10000000, Size: 100, Total time: 3.548 sec, Avg. time: 3.548e-7 sec
Iterations: 10000000, Size: 1000, Total time: 3.368 sec, Avg. time: 3.368e-7 sec
Iterations: 10000000, Size: 10000, Total time: 3.549 sec, Avg. time: 3.549e-7 sec
Iterations: 10000000, Size: 100000, Total time: 3.407 sec, Avg. time: 3.407e-7 sec
Iterations: 10000000, Size: 1000000, Total time: 4.557 sec, Avg. time: 4.557e-7 sec
Iterations: 10000000, Size: 2000000, Total time: 3.263 sec, Avg. time: 3.263e-7 sec
Iterations: 10000000, Size: 3000000, Total time: 3.574 sec, Avg. time: 3.574e-7 sec
Iterations: 10000000, Size: 4000000, Total time: 4.047 sec, Avg. time: 4.047e-7 sec
Iterations: 10000000, Size: 5000000, Total time: 3.628 sec, Avg. time: 3.628e-7 sec
正如我们所看到的,平均。在单个 count() 中花费的时间大约是恒定的,大约为 0.4 微秒,与数组的大小无关。
结论:
PHP 本身以一种有效的方式跟踪数组中元素的数量(count() 的运行时间成本为 O(1))。无需使用额外的变量来提高效率。
count() 对于语法清晰度和效率都是健康的。