Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
I am actually genuinely interested in this!
What are the ups and downs of each of them? -
LMagnus20577yThe second one takes slightly less brain power to read.
In terms of performance you'll not notice any difference, so go for the one your co-workers will need to use slightly less brain power on. -
sha-i2067yThe second one lets you see the count and not the final index in 0-based arrays which is why I like it...
for (int i = 0; i < myList.Count; i++) { ... -
Root797757yBoth:
<= for when the number itself has meaning.
< for limits or lengths of arrays/strings/etc.
Pick the one that conveys the most information about your intent in the most readable way. -
Cyan1011717yIt depends on what the loop is for, if you want people to know it's specifically running 9 times then the first one
-
If it is to loop through a collection, clearly the second one. When you need a specific range I rather like the first.
-
This has actually been analysed.
Dijkstra wrote about bounds checking and the best way that minimises errors.
Basically:
0 <= x < N
is the way to do it. -
mt3o19137y@LoveBytes @sha-i it is widely said that explicitly stating collection.size() is not slower than keeping local copy of the size.
Related Rants
Loop counter conditions.
10 loops for example in this scenario:
i<=9
OR
i<10
Was arguing with a co-worker all week over this 😂
undefined
loops
conditions