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?
In the long run declaring a temp array would be quicker because the jvm has to compute the offset when accessing an array element.
Use a profiling tool and see which is quicker for your use, but I'd caution that unless you're doing something really intensive that is very time-sensitive, this isn't going to be a huge improvement.
The second approach is definitely faster. But you can help even more with the final
keyword:
final float x = shape.vertices[0].x;
final float y = shape.vertices[0].y;
final int rightEdge = x + shape.width;
if ((x >= fromX && x <= toX) || // left side of shape in screen
(x <= fromX && rightEdge >= fromX) || // right side of shape in screen
(x >= fromX && rightEdge <= toX)) { // shape fully in screen
// ...
}
Not a significant improvement of course (but still an improvement and also makes the intent clear). You can read this discussion: http://old.nabble.com/Making-copy-of-a-reference-to-ReentrantLock-tt30730392.html#a30733348
Run the code through a profiler to answer the question for your usecase.
The answer to this will probably be JVM specific. The Oracle HotSpot JVM is going to perform differently than OpenJDK or IBM's JDK. Timings will depend on how the JVM optimizes the byte code, what it decides to compile while it is running. Server vs client mode will probably make a difference too.
So aim for readability. Optimize after profiling and determining that section of code is the problem.
The second approach is faster, but will consume more memory. But the performance increases is only nano seconds, unless you array size is huge.
I would recommend second approach, simply because it is a lot more readable and helps a lot the maintainability.
Performance gains, except if your array is huge, are really really small.
Readability gains, on the other hand, are always good to take.
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.