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

StackOverflow https://stackoverflow.com/questions/13748872

Question

I'm making a program for myself and this question popped up. This program deals with graphics so I have to keep performance in mind.

Is there a difference in performance if I use several variables or if I use an array with hard coded indexes? If there is, 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.

Was it helpful?

Solution

You are most likely 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 learn how to optimize code. For example it might realize that a parameter to a method is never assigned and thus constant. But it does not do so for each element of an array. An array is just considered as one huge mutable variable. So you are more likely to get optimal code when using separate variables.

OTHER TIPS

There definitely is a memory difference.

Your first scenario uses (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);

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

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

You should think one step further:

Where does the x,y,z values come from?

Do you have an x[] an y[] and an z[] array for the coordinates? Where do you iterate?

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

In doubt this would be faster to iterate 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);

    }

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top