加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 01:02:53 所属栏目:Java 来源:网络整理
导读:什么是 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
什么是 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

        // ...
    }

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读