What is faster in Java. Accessing an array index directly multiple times, or saving the value of the array index to a new variable and use this for following compution?
Array access could be faster. Note the following program:
public class ArraySpeedTest{
public static void main(String [] args){
float x = 4.4f;
float [] xArr = new float[1];
xArr[0] = 4.4f;
long time1 = System.nanoTime();
for(int i = 0 ; i < 1000*1000*1000; i++){
if(x > 1 && x < 5){
}
}
long time2 = System.nanoTime();
System.out.println(time2-time1);
long time3 = System.nanoTime();
for(int i = 0 ; i < 1000*1000*1000; i++){
if(xArr[0] > 1 && xArr[0] < 5){
}
}
long time4 = System.nanoTime();
System.out.println(time4-time3);
}
}
OUTPUT:: 5290289 2130667
JVM implementations, flags, and order of the program can change the performance on the order of a few milliseconds.