Java速度访问数组索引与临时变量

时间:2012-04-19 15:33:52

标签: java arrays performance

Java的速度更快。直接多次访问数组索引,或者将数组索引的值保存到新变量中并使用它来进行后续计算?

访问索引

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

    // ...
}

临时变量

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

        // ...
    }

6 个答案:

答案 0 :(得分:7)

第二种方法肯定更快。但是,您可以使用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

    // ...
}

当然不是一个显着的改进(但仍然是一种改进,也使意图明确)。您可以阅读以下讨论:http://old.nabble.com/Making-copy-of-a-reference-to-ReentrantLock-tt30730392.html#a30733348

答案 1 :(得分:2)

从长远来看,声明临时数组会更快,因为jvm在访问数组元素时必须计算偏移量。

使用分析工具,看看哪个更快,您可以使用,但我要提醒的是,除非您正在做一些非常时间敏感的事情,否则这不会是一个巨大的进步。

答案 2 :(得分:1)

通过分析器运行代码以回答用例的问题。

对此的答案可能是特定于JVM的。 Oracle HotSpot JVM的执行方式与OpenJDK或IBM的JDK不同。计时将取决于JVM如何优化字节代码,以及它在运行时决定编译的内容。服务器与客户端模式也可能有所不同。

所以追求可读性。在分析并确定代码部分是问题之后进行优化。

答案 3 :(得分:0)

第二种方法更快,但会消耗更多内存。但性能提升只有纳秒,除非阵列大小很大。

答案 4 :(得分: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);


}

}

OUTPUT :: 5290289 2130667

JVM实现,标志和程序的顺序可以改变几毫秒的性能。

答案 5 :(得分:-1)

我会推荐第二种方法,因为它更强可读,并且有很多可维护性

性能提升,除非您的阵列很大,但实际上非常小。

另一方面,可读性增益总是很好。

相关问题