I have read that some of the JVMs out there can optimize code execution by removing bounds checking. What I am trying to figure out is what coding technique will work better.
In method example1 below would the JVM ever figure it out and eliminate the bounds checking of the source[index] reference?
Is example2 the better code practice? It would seem so, but in some algorithms inside a loop the index being out of bounds is a normal condition. So you don't want to be generating tons of Exception objects inside that loop.
public void example1(int [] source, int index) {
if (index >= 0 && index < source.length)
System.out.println("Value is " + source[index]);
else
System.out.println("Out of range: " + index);
}
public void example2(int [] source, int index) {
try {
System.out.println("Value is " + source[index]);
} catch (IndexOutOfBoundsException exp) {
System.out.println("Out of range: " + index);
}
}
These code fragments are only representational. I am aware that in these examples the bounds-checking will hardly matter to performance. However I am working on an embedded protocol application where the redundant bounds checking will add up.