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

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

访问索引

if ((shape.vertices[0].x >= fromX && shape.vertices[0].x <= toX) || // left side of shape in screen (shape.vertices[0].x = 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) || // 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

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

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

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

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

因此,目标是可读性。 在分析并确定代码段是问题之后进行优化。

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

数组访问速度可能更快。 请注意以下程序:

 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); } } 

输出:: 5290289 2130667

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

我建议使用第二种方法,因为它更具可读性,并且有助于提高可维护性

除非arrays很大,否则性能提升真的很小。

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