gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:03:22 26 4
gpt4 key购买 nike

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

关于Java 速度访问数组索引与临时变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10231585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com