Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best idiom for a decrementing loop

Tags:

java

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?

like image 223
Lawrence Dol Avatar asked Nov 30 '22 19:11

Lawrence Dol


2 Answers

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

like image 119
Matthew Sowders Avatar answered Dec 14 '22 23:12

Matthew Sowders


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.
  • Comparison to zero is usually faster than comparison to other constants. It is a single instruction that examines a single value on the stack. Other comparisons use one instruction to push a constant onto the stack and another instruction to compare the top two values.
like image 23
erickson Avatar answered Dec 15 '22 01:12

erickson