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

And*_*den 7 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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

临时变量

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

        // ...
    }
Run Code Online (Sandbox Code Playgroud)

Eug*_*sky 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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

  • @EugeneRetunsky它没有任何影响.生成的字节代码与`final`相同或不相同.亲自尝试看看(使用`javap -c`). (3认同)