What's the best/preferred idiom for a decrementing for loop, and why?
for(int idx=(len-1); idx>=0; idx--) {...}
or
for(int idx=(len-1); idx>-1; idx--) {...}
or (based on sylvarking's answer, but using for to constrain the index scope)
for(int idx=len; idx-->0; ) {...}
Is one or the other more likely to trip up another developer?
I recommend the following because comparison against zero is optimized at the byte code level.
for(int idx=(len-1); idx>=0; idx--) {...}
This is a suggestion from Java Performance Tuning by Jack Shirazi
Another array-oriented variant you might see is this:
int n = foo.length;
while (n-- > 0) {
/* Do something with foo[n] */
}
Of the options you show, I prefer the first.
0
is (arguably) more readable than -1
. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With