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?
If you store the result of a.length in variable, it won’t be any “faster” if it is actually so. In any event, it is rarely worth worrying about the performance of such a trivial operation. Focus on the readability of the method.
For me, counting up is more readable.