Java speed access array index versus temp variable

前端 未结 6 807
情深已故
情深已故 2021-01-17 13:21

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?

6条回答
  •  时光说笑
    2021-01-17 14:18

    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.

提交回复
热议问题