在 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.php 状态:"The above code can be slow, because the array size is fetched on every iteration. Since the size never changes, the loop be easily optimized by using an intermediate variable to store the size instead of repeatedly calling count():"

翻译真的那么笨吗?

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

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

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

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