Java速度访问数组索引与临时变量 [英] Java speed access array index versus temp variable

查看:282
本文介绍了Java速度访问数组索引与临时变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

访问索引

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

        // ...
    }


推荐答案

第二种方法肯定更快。但是你可以使用 final 关键字提供更多帮助:

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

    // ...
}

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

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

这篇关于Java速度访问数组索引与临时变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆