Counting down to zero in contrast to counting up to length - 1

Posted by Helper Method on Stack Overflow See other posts from Stack Overflow or by Helper Method
Published on 2010-03-23T23:04:44Z Indexed on 2010/03/23 23:13 UTC
Read the original article Hit count: 275

Filed under:
|

Is it recommended to count in small loops (where possible) down from length - 1 to zero instead of counting up to length - 1?

1.) Counting down

for (int i = a.length - 1; i >= 0; i--) {
    if (a[i] == key) return i;
}

2.) Counting up

for (int i = 0; i < a.length; i++) {
    if (a[i] == key) return i;
}

The first one is slightly faster that the second one (because comparing to zero is faster) but is a little more error-prone in my opinion. Besides, the first one could maybe not be optimized by future improvements of the JVM. Any ideas on that?

© Stack Overflow or respective owner

Related posts about java

Related posts about best-practices