这是计算for语句中一个数组大小的更好方法


Which is the better way to calculate the size of one array in a for statement?

哪个更快?有理由使用其中一个而不是另一个吗
for($i = 0; $i < count($array); ++$i){ ... }

for($i = 0, $size = count($array); $i < $size; ++$i){ ... }

http://php.net/manual/en/control-structures.for.phpstates:"上面的代码可能很慢,因为每次迭代都会获取数组大小。由于大小永远不会改变,因此可以通过使用中间变量来存储大小,而不是重复调用count()来轻松优化循环:"

翻译真的那么笨吗?

在这种情况下,每次迭代都必须调用函数count(),时间复杂度为O(n):

for($i = 0; $i < count($array); ++$i){ ... }

在这种情况下,在te开始时调用一次count(),并使用$size的存储值,时间复杂度为O(1)。这种情况更快:

for($i = 0, $size = count($array); $i < $size; ++$i){ ... }