Java Fast Access Array Index vs. Temporary Variable

Which is faster in Java. Access to the index of the array several times at once, or save the value of the index of the array into a new variable and use this for later compilation?

acces index

if ((shape.vertices[0].x >= fromX && shape.vertices[0].x <= toX) || // left side of shape in screen
    (shape.vertices[0].x <= fromX && shape.vertices[0].x + shape.width >= fromX) || // right side of shape in screen
    (shape.vertices[0].x >= fromX && shape.vertices[0].x + shape.width <= toX)) { // shape fully in screen

    // ...
}

temporary variable

float x = shape.vertices[0].x;
float y = shape.vertices[0].y;
if ((x >= fromX && x <= toX) || // left side of shape in screen
    (x <= fromX && x + shape.width >= fromX) || // right side of shape in screen
    (x >= fromX && x + shape.width <= toX)) { // shape fully in screen

        // ...
    }
+5
source share
6 answers

The second approach is definitely faster. But you can help even more with the keyword final:

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 in the course (but still an improvement, and also makes the intention understandable). You can read this discussion: http://old.nabble.com/Making-copy-of-a-reference-to-ReentrantLock-tt30730392.html#a30733348

+7
source

temp , jvm .

, , , , - , , .

+2

, .

, , JVM. Oracle HotSpot JVM , OpenJDK IBM JDK. , JVM , . , , .

, . , .

+1

, . - nano , .

0

. :

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);


}

}

:: 5290289 2130667

, JVM .

0

, , .

The performance increase, except when the array is massive, is really very small.

Readability factors, on the other hand, are always good.

-1
source

All Articles