This is just a clarification by example of how situational this is.
I tested executions of the "normal" for loop for (int i = 0; i < list.size(); i++)
and a micro optimized for loop for (int i = -1, size = list.size(); ++i < size;)
. I ran the tests both in eclipse from the command line and noticed a HUGE difference.
Results from running in eclipse:
Time for Original: 32552 ms Time for MicroOptimized 32707 ms
Fastest Loop: Original
Slowest loop takes 0.47616121897272057% more time
Results from running from commandline:
Time for Original: 274489 ms Time for MicroOptimized 30516 ms
Fastest Loop: MicroOptimized
Slowest loop takes 799.4920697339101% more time
So in eclipse, the two for loops take the same time, but when run from the command line, the original version takes 800% more time than the microoptimized version. The magnitude of the difference blows my mind. I guess that eclipse uses a different JVM which applies some smart optimization tricks.
This doesn't mean that you should start using the micro optimized version however. In almost all cases, the lists you iterate over will likely be so small that the performance difference is negligible. And the readability gained from using the standard version which everyone will recognize and understand much more quickly is more beneficial than a non-noticeable performance increase.
For completeness, this is the code I ran:
public static void main(String[] args) {
List<Byte> list = initializeList();
byte value = 0;
final int NUM_LOOPS = 100;
long startOriginal, startOptimized, endOriginal, endOptimized;
startOptimized = System.currentTimeMillis();
for (int j = 0; j < NUM_LOOPS; j++) {
for (int i = -1, size = list.size(); ++i < size;) {
value = list.get(i);
}
}
endOptimized = System.currentTimeMillis();
startOriginal = System.currentTimeMillis();
for (int j = 0; j < NUM_LOOPS; j++) {
for (int i = 0; i < list.size(); i++) {
value = list.get(i);
}
}
endOriginal = System.currentTimeMillis();
System.out.println(value);
printResults(startOriginal, endOriginal, startOptimized, endOptimized);
}
private static void printResults(long startOriginal, long endOriginal,
long startOptimized, long endOptimized) {
long timeOriginal = endOriginal - startOriginal;
long timeOptimized = endOptimized - startOptimized;
long diff = Math.abs(timeOriginal - timeOptimized);
long min = Math.min(timeOriginal, timeOptimized);
System.out.println("Time for Original: " + timeOriginal + " ms"
+ " Time for MicroOptimized " + timeOptimized + " ms");
System.out.println("Fastest Loop: "
+ ((timeOriginal < timeOptimized) ? "Original"
: "MicroOptimized"));
System.out.println("Slowest loop takes " + ((double) 100 * diff / min)
+ "% more time");
}
public static List<Byte> initializeList(){
List<Byte> list = new ArrayList<Byte>();
final Byte ONE = new Byte((byte) 1);
for (int i = 0; i < Integer.MAX_VALUE / 10; i++) {
list.add(ONE);
}
return list;
}
}