是否应使用<或< =在for循环中 [英] Should one use < or <= in a for loop

查看:91
本文介绍了是否应使用<或< =在for循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果必须循环遍历7次,您将使用:

If you had to iterate through a loop 7 times, would you use:

for (int i = 0; i < 7; i++)

或:

for (int i = 0; i <= 6; i++)

有两个注意事项:


  • 性能

  • 可读性

为了提高性能,我假设使用Java或C#。是否使用小于或小于或等于是否重要?如果您有其他语言的见解,请指出。

For performance I'm assuming Java or C#. Does it matter if "less than" or "less than or equal to" is used? If you have insight for a different language, please indicate which.

出于可读性考虑,我假设基于0的数组。

For readability I'm assuming 0-based arrays.

UPD:我提到的从0开始的数组可能会使您感到困惑。我不是在谈论遍历数组元素。只是一个一般的循环。

UPD: My mention of 0-based arrays may have confused things. I'm not talking about iterating through array elements. Just a general loop.

使用常量可以解释这个神奇的数字是一个很好的认识。因此,如果我有 int NUMBER_OF_THINGS = 7 ,那么 i< = NUM​​BER_OF_THINGS-1 看起来很奇怪,不是吗

There is a good point below about using a constant to which would explain what this magic number is. So if I had "int NUMBER_OF_THINGS = 7" then "i <= NUMBER_OF_THINGS - 1" would look weird, wouldn't it.

推荐答案

第一个是更多惯用。特别是,它指示(从0开始)迭代次数。当使用基于1的东西(例如JDBC,IIRC)时,我可能会想使用< =。因此:

The first is more idiomatic. In particular, it indicates (in a 0-based sense) the number of iterations. When using something 1-based (e.g. JDBC, IIRC) I might be tempted to use <=. So:

for (int i=0; i < count; i++) // For 0-based APIs

for (int i=1; i <= count; i++) // For 1-based APIs

我希望在实际代码中,性能差异不会很小。

I would expect the performance difference to be insignificantly small in real-world code.

这篇关于是否应使用&lt;或&lt; =在for循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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