为什么计数不如$ count [英] Why count is bad than $count

查看:109
本文介绍了为什么计数不如$ count的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是回顾不同问题的答案,以了解更多。我看到一个答案,它表示在php中写作是不好的习惯


$ b $ ($ i = 0; $ i



<它说在循环中调用count函数会降低代码的速度。关于这个问题的意见的讨论并不清楚。我想知道为什么这不是好的做法。你应该这样做:

解决方案

b $ b

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



<这样做的原因是因为如果你在for循环中放置 count($ array),那么每次迭代都要调用count函数,这会减慢速度。


但是,如果将计数放入一个变量中,则这是一个静态数字,不必每次重新计算。


I was just reviewing the answers to different questions to learn more. I saw an answer which says that it is bad practice in php to write

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

It says that calling the count function in the loop reduces the speed of the code. The discussion in the comments on this question was not clear. I want to know why it is not good practice. What should be the alternative way of doing this?

解决方案

You should do this instead:

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

The reason for doing this is because if you put the count($array) inside the for loop then the count function would have to be called for every iteration which slows down speed.

However, if you put the count into a variable, it is a static number that won't have to be recalculated every time.

这篇关于为什么计数不如$ count的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆