Counting down to zero in contrast to counting up to length - 1
- by Helper Method
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?