简体   繁体   English

在for语句中计算一个数组大小的更好方法是哪种?

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

Which is faster? 哪个更快? are there reasons to use one over the other? 有什么理由要使用另一个?
for($i = 0; $i < count($array); ++$i){ ... }
OR 要么
for($i = 0, $size = count($array); $i < $size; ++$i){ ... }

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

Is the interpreter actually that dumb? 口译员真的那么笨吗?

In this case in each iteration you must call the function count() , the time complexity is O(n) : 在这种情况下,每次迭代都必须调用函数count() ,时间复杂度为O(n)

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

In this case you call once count() at te begining, and you use the store value of $size , time complexity is O(1) . 在这种情况下,您从te调用一次count() ,并使用$size的存储值,时间复杂度为O(1) This case is more faster: 这种情况会更快:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM