Should one use < or <= in a for loop

Eugene Katz picture Eugene Katz · Oct 8, 2008 · Viewed 36.6k times · Source

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

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

or:

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

There are two considerations:

  • performance
  • readability

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.

For readability I'm assuming 0-based arrays.

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

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.

Answer

Jon Skeet picture Jon Skeet · Oct 8, 2008

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.