Java: is there a performance difference between using n variables or using elements of a hard coded array?

I am creating a program for myself, and this question has arisen. This program deals with graphics, so I have to remember performance.

Is there a performance difference if I use multiple variables or use an array with hard-coded indices? If so, which is better?

To illustrate:

R = (X * 3.2406) + (Y * -1.5372) + (Z * -0.4986); G = (X * -0.9689) + (Y * 1.8758) + (Z * 0.0415); B = (X * 0.0557) + (Y * -0.2040) + (Z * 1.0570); 

or

 RGB[0] = (XYZ[0] * 3.2406) + (XYZ[1] * -1.5372) + (XYZ[2] * -0.4986); RGB[1] = (XYZ[0] * -0.9689) + (XYZ[1] * 1.8758) + (XYZ[2] * 0.0415); RGB[2] = (XYZ[0] * 0.0557) + (XYZ[1] * -0.2040) + (XYZ[2] * 1.0570); 

Thanks in advance.

+4
source share
3 answers

Most likely you are faster with separate variables.

Why? The JVM optimizes your code at runtime to make it faster. It tracks the flow and values โ€‹โ€‹of each variable to find out how to optimize the code. For example, he can understand that a method parameter is never assigned, and thus is constant. But this is not the case for each element of the array. An array is considered only as one huge mutable variable. Thus, you are more likely to get the best code when using individual variables.

+3
source

Definitely a difference in memory.

In the first scenario, it is used (assuming doubles):

 8 8 8 8 = 24 bytes R = (X * 3.2406) + (Y * -1.5372) + (Z * -0.4986); 8 = 32 bytes G = (X * -0.9689) + (Y * 1.8758) + (Z * 0.0415); 8 = 40 bytes B = (X * 0.0557) + (Y * -0.2040) + (Z * 1.0570); 

The second scenario uses:

 12 + 8 12 + 8 8 8 = 56 bytes RGB[0] = (XYZ[0] * 3.2406) + (XYZ[1] * -1.5372) + (XYZ[2] * -0.4986); 8 = 64 bytes RGB[1] = (XYZ[0] * -0.9689) + (XYZ[1] * 1.8758) + (XYZ[2] * 0.0415); 8 = 72 bytes RGB[2] = (XYZ[0] * 0.0557) + (XYZ[1] * -0.2040) + (XYZ[2] * 1.0570); 

Link: http://www.javamex.com/tutorials/memory/object_memory_usage.shtml

+3
source

You should consider the following:

Where do x, y, z come from?

Do you have x [] y [] and z [] array for coordinates? Where do you repeat?

 for (int i = 0; i < len; i++) { process(x[i], y[i], z[i]; } 

In doubt, this will be faster than iterating inside:

public void process (double x [], double y [], double z []) {

  for (int i = 0; i < len; i++) { rbgb[0] = (x[i] * 3.24606 + y[i] * 1.5372 + z[i] * -0.4986); } 

}

0
source

All Articles